Reputation: 18781
I'm trying to match a patterned with regex except when the pattern is escaped.
Test text:
This is AT\&T® is really cool Regex
You can see with my \& I'm manually escaping. And therefore, do not want the regex to match.
Regex:
const str = 'This is AT\&T® is really cool Regex'
str.replace(/\&(.*?)\;/g, '<sup>&$1;</sup>');
Expected output
This is AT&T<sup>®</sup> is really cool Regex
Hard to explain I guess but when the start of this regex looks for a &
and ends with a ;
however, if &
is preceded with at \
like \&
than do not match and look for the next \&(.*?)\;
Upvotes: 0
Views: 64
Reputation: 441
You can use negative lookbehind
This regex works fine with the example
/(?<!\\)\&(.*?)\;/g
To workaround in JS you can use [^\\]
that will match everything except backslash. The overall regex /[^\\]\&(.*?)\;/g
It works for your example.
Upvotes: 1
Reputation: 4560
Since JavaScript have no support for lookbehind assertions - it is possible to add some custom substitution logic to achieve desired results. I've updated test string with examples of different kinds of html entities for test purposes:
const str = '&T;his is AT\\&T® is & really &12345; &xAB05; \\&cool; Regex'
console.log(str.replace(/&([a-z]+|[0-9]{1,5}|x[0-9a-f]{1,4});/ig, function (m0, m1, index, str) {
return (str.substr(index - 1, 1) !== '\\') ? '<sup>' + m0 + '</sup>' : m0;
}));
Upvotes: 0