I want to check if given text is surrounded by curly brackets but also want to ignore them when they are "escaped". So I want to match {Something}
but not \{Something\}
...
What is the easiest way to do that?
I want to check if given text is surrounded by curly brackets but also want to ignore them when they are "escaped". So I want to match {Something}
but not \{Something\}
...
What is the easiest way to do that?
One could use negative look-behind, that is that no backslash was preceding. But if the backslash is a regular escape character, the \\{
would be a backslash plus a brace.
For that case do:
Pattern pattern = Pattern.compile("(\\\\.|[^{\\\\])*\\{" // All upto open brace
+ "(\\\\.|[^}\\\\])*" // The sought, $2
+ "\\}"); // Closing brace
String s = "...";
Matcher m = pattern.matcher(s);
while (m.find()) {
System.out.println(m.group(2);
}
The pattern
(
\\\\. backslash followed by any char
| or
[^{\\\\] not one of: '{' or backslash
)