Reputation: 181
given 3 lines , how can I extract 2nd line using regular expression ?
line1
line2
line3
I used
pattern = Pattern.compile("line1.*(.*?).*line3");
But nothing appears
Upvotes: 0
Views: 679
Reputation: 785256
You can use Pattern.DOTALL flag like this:
String str = "line1\nline2\nline3";
Pattern pt = Pattern.compile("line1\n(.+?)\nline3", Pattern.DOTALL);
Matcher m = pt.matcher(str);
while (m.find())
System.out.printf("Matched - [%s]%n", m.group(1)); // outputs [line2]
Upvotes: 1
Reputation: 13356
You can extract everything between two non-empty lines:
(?<=.+\n).+(?=\n.+)
Upvotes: 0
Reputation: 12212
Try pattern = Pattern.compile("line1.*?(.*?).*?line3", Pattern.DOTALL | Pattern.MULTILINE);
Upvotes: 0
Reputation: 6921
This won't work, since your first .*
matches everything up to line3. Your reluctant match gets lost, as does the second .*
.
Try to specify the line breaks (^ and $) after line1 / before line3.
Upvotes: 0