John Abraham
John Abraham

Reputation: 18781

Match pattern except under one condition Regex

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>&reg;</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

Answers (2)

Anton
Anton

Reputation: 441

You can use negative lookbehind This regex works fine with the example /(?<!\\)\&(.*?)\;/g

Edit 1

To workaround in JS you can use [^\\] that will match everything except backslash. The overall regex /[^\\]\&(.*?)\;/g It works for your example.

Upvotes: 1

Flying
Flying

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&reg; 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

Related Questions