Reputation: 86747
For the construct {123{a,b}}
I want to match {123{
and }}
.
This is done by regex: {(.*?){|}}
BUT: now I want to use the same expression to run on {a,b}
and match {
and }
only.
Therefore I somehow have to make the 2nd {
optional. But how?
I'm using http://gskinner.com/RegExr/ to test on the fly.
Upvotes: 2
Views: 58
Reputation: 7804
Try using this code:
Pattern pattern = Pattern.compile("\\{(.*\\{|[^\\}]*)");
Matcher matcher1 = pattern.matcher("{123{a,b}}");
Matcher matcher2 = pattern.matcher("{a,b}");
while (matcher1.find()) {
System.out.println(matcher1.group());
}
while (matcher2.find()) {
System.out.println(matcher2.group());
}
Output:
{123{
{a,b
Upvotes: 0
Reputation: 213263
You can use following regex:
(?:{.*?)?{|}}?
This makes all the content outside the inner braces optional.
(?:{.*?)? // Contents before the opening inner brace '{' (Optional)
{
|
}
}? // Last brace (Optional)
See demo on http://regexr.com?35t3r
Upvotes: 3