简体   繁体   English

正则表达式以匹配未链接的特定文本

[英]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, ie 我想用JavaScript写一个正则表达式来匹配特定的文本,只有当它不是html链接的一部分时,即

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. 我非常感谢您提供完善正则表达式的帮助。

You can use a negative look-behind to get the opening <a href=... : 您可以使用负向后看来获取开头<a href=...

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

Hope that works for you. 希望对您有用。

Thanks for the very quick and helpful answers. 感谢您提供快速而实用的答案。 Just to clarify, the regular expression I ended up using was 为了澄清起见,我最终使用的正则表达式是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM