0

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?

zduny
  • 2,481
  • 1
  • 27
  • 49
  • the regex would be something like `[^\]\{(.*[^\])\}` (not a bracket, curly bracket, anything, not a bracket, curly bracket. What's inside the curly brackets is in the first group) – njzk2 Apr 28 '14 at 20:59
  • 2
    If you don't want to use a regex, you can check the string with the methods `.startsWith("{")` and `.endsWith("}")`. – AntonH Apr 28 '14 at 21:01

1 Answers1

0

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
)
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138