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

Time:11-30

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.

CodePudding user response:

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>).)*(?=--)

CodePudding user response:

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

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

  • Related