简体   繁体   中英

Substring between lines using Regular Expression Java

Hi I am having following string

abc test ...
interface
somedata ...
xxx ...
!
sdfff as ##
example
yyy sdd @# .
!

I have a requirement that I want to find content between a line having word "interface" or "example" and a line "!".
Required output will be something like below

String[] output= {"somedata ...\nxxx ...\n","yyy sdd @# .\n"} ;

I can do this manually using substring and iteration . But I want to achieve this using regular expression. Is it possible?

This is what I have tried

String sample="abc\ninterface\nsomedata\nxxx\n!\nsdfff\ninterface\nyyy\n!\n";
    Pattern pattern = Pattern.compile("(?m)\ninterface(.*?)\n!\n");
    Matcher m =pattern.matcher(sample);
    while (m.find()) {
        System.out.println(m.group());
    }

Am I Right? Please suggest a right way of doing it .

Edit :

A small change : I want to find content between a line "interface" or "example" and a line "!".

Can we achieve this too using regex ?

You could use (?s) DOTALL modifier.

String sample="abc\ninterface\nsomedata\nxxx\n!\nsdfff\ninterface\nyyy\n!\n";
Pattern pattern = Pattern.compile("(?s)(?<=\\ninterface\\n).*?(?=\\n!\\n)");//Pattern.compile("(?m)^.*$");
Matcher m =pattern.matcher(sample);
while (m.find()) {
    System.out.println(m.group());
}

Output:

somedata
xxx
yyy

Note that the input in your example is different.

  • (?<=\\\\ninterface\\\\n) Asserts that the match must be preceded by the characters which are matched by the pattern present inside the positive lookbehind.

  • (?=\\\\n!\\\\n) Asserts that the match must be followed by the characters which are matched by the pattern present inside the positive lookahead.

Update:

Pattern pattern = Pattern.compile("(?s)(?<=\\n(?:example|interface)\\n).*?(?=\\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