Reputation: 5167
I have the following string I am trying to capture from (let's call it output
):
ltm pool TEST_POOL {
Some strings
above headers
records {
baz:1 {
ANY STRING
HERE
}
foobar:23 {
ALSO ANY
STRING HERE
}
}
members {
qux:45 {
ALSO ANY
STRINGS HERE
}
bash:2 {
AND ANY
STRING HERE
}
topaz:789 {
AND ANY
STRING HERE
}
}
Some strings
below headers
}
Consider each line of output
to be separated by a typical line break. For the sake of this question, let's refer to records
and members
as "titles" and baz
, foobar
, qux
, bash
, and topaz
as "headers". I am trying to formulate a regex in Java that will capture all headers between the brackets of a given title in a find loop. For example, given we want to find all headers of title members
with this code:
String regex = TODO; // members\\s\\{ contained in regex
final Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(output);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
The output should be ...
qux
bash
topaz
And should exclude baz
and foobar
because they are contained within the brackets of a different "title". There can be any number of titles and any number of headers. Some help in formulating a regex to solve this problem would be much appreciated.
Upvotes: 0
Views: 95
Reputation: 785856
You can use this regex using \G
that asserts position at the end of the previous match or the start of the string for the first match:
(?:\bmembers\s*\{|(?<!^)\G[^{]+\{[^}]+\})\s*?\n\s*([^:{}]+)(?=:\d)
OR:
(?:\brecords\s*\{|(?<!^)\G[^{]+\{[^}]+\})\s*?\n\s*([^:{}]+)(?=:\d)
This is assuming there are no nested and escaped {
and }
.
Upvotes: 1