I want to extract the next line data of a text file if regex pattern matches in Java. I am able to detect and match the pattern data in a text file, But unable to print the next line of pattern data.
Test data:
*** Explorer
GenV Deno Znet
Regular Expression for matching the Explorer
[*\\+]+[\\s+]+[Explorer]+[:]
Kindly help me on how to get the next line if *** Explorer pattern is found.
You can use this regex with a capturing group for the next line after your search pattern:
[*]+\s+Explorer\R(.*)
Next line is captured in group #1
Regex Breakup:
[*]+\s+Explorer - Match your search pattern\R - Match any newline character(.*) - Match and captured full line in group #1In Java use:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "[*]+\\s+Explorer\\R(.*)";
final String input = "*** Explorer\nGenV Deno Znet";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("match: " + matcher.group(1));
}
Well, for starters the regex is not going to match "*** Explorer"
It will match "*** Explorer:"
If this is java, can't you just read the next line?
while ((lineText = lineReader.readLine()) != null) {
hasMatch = lineText.matches(regex);
if(hasMatch) {
lineText = lineReader.readLine();
System.out.println(lineText);
}
}
Works for me.