0

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

1
  • 2
    try the DOTALL option when compiling the regex. Commented Jan 24, 2012 at 15:27

4 Answers 4

1

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]
Sign up to request clarification or add additional context in comments.

3 Comments

This seems extract \n , any way to remove them ?
In your example it worked , in my example it is still giving me the new lines . Any other ways to remove them ? I tried string = string.replaceAll("\\\\n", ""); but didn't work
You can call replaceAll as well but if you use my updated RegEx then it won't even capture \n thus eliminating the need to call replaceAll
0

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.

Comments

0

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

1 Comment

I don't think this works - won't the reluctant group in the middle will resolve to 0 characters?
0

You can extract everything between two non-empty lines:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.