Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression to match specific text not linked

I would like to write a regular expression in javascript to match specific text, only when it is not part of an html link, i.e.

match <a href="/link/page1">match text</a>

would not be matched, but

match text

or

<p>match text</p>

would be matched.

(The "match text" will change each time the search is run - I will use something like

var tmpStr = new RegExp("\bmatch text\b","g");

where the value of "match text" is read from a database.)

So far my best effort at a regular expression is

\bmatch text\b(?!</a>)

This deals with the closing , but not the initial . This will probably work fine for my purposes, but it does not seem ideal. I'd appreciate any help with refining the regular expression.

like image 850
Tomba Avatar asked Dec 01 '25 21:12

Tomba


2 Answers

You can use a negative look-behind to get the opening <a href=...:

var tmpStr = new RegExp('(?<!<a.*?>)match text(?!</a>)');

Hope that works for you.

like image 112
Eric Wendelin Avatar answered Dec 04 '25 09:12

Eric Wendelin


Thanks for the very quick and helpful answers. Just to clarify, the regular expression I ended up using was

(?!<a.*?>)\bmatch text\b(?!</a>)
like image 44
Tomba Avatar answered Dec 04 '25 09:12

Tomba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!