Detect text between braces excluding strings. Partial code done

I have almost zero experience with Regex. What I'm trying to do is to match text between braces, like this:

{([^}]*)}

Demo: https://regex101.com/r/tG7kC0/16

but do not match them when they are between quotes (single and double) and with escaping characters, like this:

(["'])(?:(?!\1)[^\\]|\\.)*\1?

Demo: https://regex101.com/r/tG7kC0/15

I managed to create both regexes and I'm not sure if they are good or not. The thing is that I got them working separately. Now I want to unify them but I have no idea. How can I achieve this?

Upvotes: 0

Views: 50

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

In Javascript there's no real way to do that with the pattern only.

A simple workaround consists to join the two patterns in an alternation and to test the capture groups:

var re = /(["'])(?:(?!\1)[^\\]|\\[\s\S])*\1?|{([^}]*)}/g;
var str = 'asd + {ASD} + {A-._&SD} + "asd\\"{A-.\'_&SD}" + \'a\\\'s\\\\d\' + "" + \'\'';
var m;
while ((m = re.exec(str)) !== null) {
  if (!m[1])
      console.log(m[2]);
}

In a replacement context, use a function as replacement parameter to do the same test:

var result = str.replace(re, function (m, g1, g2) {
    if (g1) return m;
    // do what you want with g2
    return '#' + g2 + '#';
}); 

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use the following regex pattern:

\{([^}\"']+)\}(?!['"])

https://regex101.com/r/tG7kC0/21

(?!['"]) - lookahead negative assertion, matches words enclosed with curly braces if they are not between quotes

Upvotes: 1

Related Questions