如何使用负搜索进行正则表达式?

How to regex with negative search?

我想在文档中搜索以下字符串

<whoName>[substring]</whoName>

其中子字符串 != "self"

所以

<whoName>other</whoName> 

会通过。

但是

<whoName>self</whoName> 

会失败

您可以使用这个基于负前瞻的正则表达式:

<(whoName)>(?!self\s*<).*?<\/>

RegEx Demo

正则表达式分解:

<(whoName)>  # Match <whoName> and capture it ()
(?!self\s*<) # Negative lookahead that means current position is not followed by literal 
             # self followed by 0 or more spaces and <
.*?          # Match 0 or more characters (non-greedy)
<\/>       # Match closing tag using back-reference to captured group #1

使用这个正则表达式:

^<whoName>((?!self<).)*</whoName>

已在 notepad++ 和 regex101 中测试

您可以找到解决方案 here

你可以使用像

这样的东西
<whoName>(?!self)[a-z0-9]*<\/whoName>

(在这里试试这个:https://regex101.com/r/vW8sP3/1)。

正如你想象的那样,相关部分是 (?!self)