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.
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.");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.