Reputation: 401
I m trying to use regex to match the following string
[one[two[three[four|five]|six|seven]
I wanted them in three groups
[one[two[three
, [four|five]
,|six|seven]
This is what i have come up with so far
(\\].*) for |six|seven] and `(\\[.*\\[)` for [one[two[three
and I m finding it difficult to match the last group which is [four|five]
Upvotes: 0
Views: 34
Reputation: 893
With the import:
import java.util.regex.*;
If the number of elements does not change (as you did not specified), you can use the following:
Pattern pattern = Pattern.compile("(\\[.+\\[.+)(\\[.+\\|.+])(\\|.+\\|.+)");
Matcher matcher = pattern.matcher("[one[two[three[four|five]|six|seven]");
//execute matching (required to iterate over groups)
boolean matched = matcher.matches();
for(int i=0; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
\
regex escapers are escaped, so that Java does not use them as escapers instead of letting them to the regex tool. I used the \
escapers because you want to match literal |
, not interpreting them as or
operator.
.
Matches every character except line terminators.
Upvotes: 1