I'd like to match parts in a string that are enclosed by braces ({}
), and refer back to the content within the braces.
The content within the braces can also contain "nested" braces, which makes it important to match the correct closing braces.
So, if another brace is opened, the following closing brace should be ignored.
As a starting point I used the following code, which should transform the String Stuff @upper{foo {bar} baz} {end}
to Stuff FOO {BAR} BAZ {end}
:
package com.stackoverflow;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExBraces {
public static void main(String[] args) {
String string = "Stuff @upper{foo {bar} baz} {end}";
Pattern pattern = Pattern.compile("@upper\\{(.*?)\\}");
Matcher matcher = pattern.matcher(string);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
String key = matcher.group(1);
if (key != null) {
matcher.appendReplacement(result, key.toUpperCase());
}
}
matcher.appendTail(result);
System.out.println(result.toString());
} // END: main()
} // END: class
In the first place I'd like to ignore escaping of braces (\{
, \}
). So there is always the same number of opening and closing braces in the correct order.
Is the a concise regular expression that can solve this problem?