简体   繁体   中英

How to extract required string in below text using regular expressions in java?

I want to extract string between first and last in the below text.

Scenario 1:

"Select statement"+"\n"+
"first"+"\n"+
"I want to extract this" +"\n"+
"I want to extract this one too"+"\n"+
"last"+"\n"+
"end of the statement"+"\n"+
"first"+"\n"+
"I want to extract this" +"\n"+
"I want to extract this one too"+"\n"+
"last"+"\n"+
"end of the statement"

Scenario 2:

"Select statement"+"\n"+
"first"+"\n"+
"I want to extract this" +"\n"+
"last"+"\n"+
"end of the statement";

What would be the regex pattern in java to do this job? Pattern should be one but it should work in both the scenarios. Thanks for your help.

You may use lookarounds.

Matcher m = Pattern.compile("(?s)(?<=\\bfirst\\n).*?(?=\\n?\\blast\\b)").matcher(s);
if(m.find())
  {
      System.out.println(m.group());
  }

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