0

i have a .txt file, which looks like this(just example):

sfafsaf102030

asdasa203040

asdaffa304050

sadasd405060

I am trying to get whole line which contains a specific(given by me) number, for example i have number "203040" and i want to receive "asdasa203040".

I tried something like this:

File file = new File("file.txt");
Scanner sc = new Scanner(file);

String pattern = "(.*)(\\d+)";
Pattern p = Pattern.compile(pattern);

System.out.println(sc.findInLine(pattern));

but it only gives me line with any number and not the one i specified. How to change it?

Thanks.

  • If you want your pattern searching for a specific number, then your `pattern` needs to contain it instead your pattern looks for any digit. – Mad Matts May 03 '16 at 17:20
  • That is my question - how to create this pattern :) Everything i come up with returns null. – Speedmaker May 03 '16 at 17:23
  • you could use regex, im not as familiar with it, or you could just read line by line, and do a simple line.contains. http://stackoverflow.com/questions/20311266/read-line-with-scanner – Brandon Ling May 03 '16 at 17:26
  • How to use patterns with variables http://stackoverflow.com/questions/10317603/use-variables-in-pattern-matcher – Mad Matts May 03 '16 at 17:28

1 Answers1

0

You don't need to use regex for this. You could just check for the line containing the number you enter:

File file = new File("file.txt");
Scanner sc = new Scanner(file);
Scanner input = new Scanner(System.in);

System.out.println(/*prompt user for input here*/);

String number = input.next();
String line;
while (sc.hasNextLine()) {
    line = sc.nextLine();
    if (line.contains(number)) {
        System.out.println(line);
        break;
    } else if (!sc.hasNextLine()) {
        System.out.println("Line not found.");
    }
}
Bethany Louise
  • 646
  • 7
  • 13