简体   繁体   中英

Capturing Multiple Groups with Regex

I'm attempting to formulate a regex in Java to capture multiple groups. Here is the string (let's call is output ) I am trying to capture from ...

ltm virtual MY_VM {
    rules {
        foo_bar
        baz
        qux-baz
    }
}

And I am trying to capture everything between the inner-most brackets, ie foo_bar , baz , and qux-baz . So far I have ...

String regex = "ltm\\svirtual\\sMY_VM\\s\\{\\s*\\n\\s*rules\\s\\{\n\\s*([^\n]*)\\s*\\}\n\\s*\\}";
final Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(output);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

But this of course only matches if I only have one item in the list. How can I modify my regex to match any number of capture groups in the inner-most brackets, assuming each group is separated by a newline character and any amount of whitespace as I have in my example?

If pair checking is not required, this should work for you:

.*\{([^}]*)

in java it would be:

String regex = ".*\\{([^}]*)";
  • Note that you need the DOTALL flag
  • read the capture group 1 , all text within inner-most brackets will be there.

Answer given by @stribizhev at this link also works for this question:

String regex = "(?:\\brules\\s+\\{|(?!^)\\G)\\s+([\\w-]+)";
final Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(output);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

I never used regExpr's in java uptill now, however if I do understand your problem correctly, the Kleene star operation will help you out.

https://en.wikipedia.org/wiki/Kleene_star

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