The concise
The concise

Reputation: 452

How to match a pattern but not when a specific tag is present

I'm trying to match: --This is a text and it <b>can contain other </b> tags--

I will wrap matched pattern with <u></u> But i'm trying to avoid <br> tag only. I.e it shouldn't match if the string has <br> in between --

text.replace(/(?:--)(?:(?!--|\s))((?!<br>).*?)(?:--)/g,'<u>$1</u>')  

Unfortunately, my regex matches

--This is a text, <b>can contain other</b>tags but don't match if <br> is present--

I don't expect it to match since <br> is present.

Upvotes: 1

Views: 104

Answers (2)

Ricky Mo
Ricky Mo

Reputation: 7718

Make (?!<br>). as a group, then quantify this group, instead of quantifying . only. Aslo, ? is redundant after * because ? means 0 or 1 while * means 0 or more, which already cover 1.

(?:--)(?:(?!--|\s))((?:(?!<br>).)*)(?:--)

Bonus: You don't need capture group if you use positive look ahead and positive look behind for --, if your environment support it. This match itself will exclude the --.

(?<=--)(?:(?!--|\s))(?:(?!<br>).)*(?=--)

Upvotes: 2

Justinas
Justinas

Reputation: 43557

First check if string does not contain <br> and then continue regex:

if (!/--.*?<br>.*?--/.test(text)) {
    text.replace(/(?:--)(?:(?!--|\s))((?!<br>).*?)(?:--)/g,'<u>$1</u>')  
}

Upvotes: 1

Related Questions