tnaser
tnaser

Reputation: 181

java regex , extract a line?

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

Answers (4)

anubhava
anubhava

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

Sufian Latif
Sufian Latif

Reputation: 13356

You can extract everything between two non-empty lines:

(?<=.+\n).+(?=\n.+)

Upvotes: 0

Piotr Gwiazda
Piotr Gwiazda

Reputation: 12212

Try pattern = Pattern.compile("line1.*?(.*?).*?line3", Pattern.DOTALL | Pattern.MULTILINE);

Upvotes: 0

Urs Reupke
Urs Reupke

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

Related Questions