Search code examples
javascriptregexlookbehind

Javascript Regex - Capture Only Unescaped Patterns


Given a string in Javascript like

{include} anything in {curly braces} but not when they are escaped like {this} and work for any position of the {brace}

I want to retrieve

  • include
  • curly braces
  • brace

I have been trying to find a way, but without look behind I am stumped.

The most important thing is to NOT get the escaped {} content. I'd be fine with something which includes the braces in the matches, if necessary.

Unfortunately, all I have managed so far is an expression like this

(?:[^//]){.*?}

But that doesn't match if the { is at the beginning of the target text.

Can anyone help me? Thanks.


Solution

  • I assume the escape char is /.

    You may use the following regex with a capturing group that will hold your values:

    /(?:^|[^\/]){([^}]*)}/g
                 ^^^^^^^
    

    See the regex demo

    Details:

    • (?:^|[^\/]) - either the start of string or a char other than /
    • { - a literal {
    • ([^}]*) - Group 1 capturing any 0+ chars other than } (add { into the class to match the shortest window between { and })
    • } - a literal }.

    var rx = /(?:^|[^\/]){([^}]*)}/g;
    var str = "{include} anything in {curly braces} but not when they are escaped like /{this} and work for any position of the {brace}";
    var m, res = [];
    while ((m = rx.exec(str)) !== null) {
      res.push(m[1]);
    }
    console.log(res);