【问题标题】:How to regex with negative search?如何使用负搜索进行正则表达式?
【发布时间】:2015-09-05 13:58:24
【问题描述】:

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

<whoName>[substring]</whoName>

where substring !="self"

所以

<whoName>other</whoName> 

会通过的。

但是

<whoName>self</whoName> 

会失败

【问题讨论】:

    标签: regex negative-lookbehind


    【解决方案1】:

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

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

    RegEx Demo

    正则表达式分解:

    <(whoName)>  # Match <whoName> and capture it ($1)
    (?!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)
    <\/\1>       # Match closing tag using back-reference to captured group #1
    

    【讨论】:

    • 此正则表达式不匹配 selfie 或任何以 self 开头的子字符串
    • 是的,我正在更新和写更多细节。请立即检查更新的答案。
    【解决方案2】:

    使用这个正则表达式:

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

    在notepad++和regex101中测试

    【讨论】:

      【解决方案3】:

      您可以找到解决方案here

      你可以使用类似的东西

      <whoName>(?!self)[a-z0-9]*<\/whoName>
      

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

      您可以想象相关部分是(?!self)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-09
        • 1970-01-01
        • 2019-02-18
        • 1970-01-01
        • 2021-05-29
        • 2016-07-19
        • 2014-10-21
        • 2015-09-22
        相关资源
        最近更新 更多