简体   繁体   中英

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

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]

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.

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

您可以提取两条非空行之间的所有内容:

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM