代码之家  ›  专栏  ›  技术社区  ›  Joe Ijam

在组中表示“not”的正则表达式

  •  6
  • Joe Ijam  · 技术社区  · 15 年前

    我有这个正则表达式:

    <(\d+)>(\w+\s\d+\s\d+(?::\d+){2})\s([\w\/\.\-]*)(.*)
    

    如果第三个组是“mswineventlog”,那么我要做的是返回false(不匹配),并为其余组返回“matched”。

    <166>Apr 28 10:46:34 AMC the remaining phrase
    <11>Apr 28 10:46:34 MSWinEventLog the remaining phrase
    <170>Apr 28 10:46:34 Avantail the remaining phrase
    <171>Apr 28 10:46:34 Avantail the remaining phrase
    <172>Apr 28 10:46:34 AMC the remaining phrase
    <173>Apr 28 10:46:34 AMC the remaining phrase
    <174>Apr 28 10:46:34 Avantail the remaining phrase
    <175>Apr 28 10:46:34 AMC the remaining phrase
    <176>Apr 28 10:46:34 AMC the remaining phrase
    <177>Apr 28 10:46:34 Avantail the remaining phrase
    <178>Apr 28 10:46:34 AMC the remaining phrase
    <179>Apr 28 10:46:34 Avantail the remaining phrase
    <180>Apr 28 10:46:34 Avantail the remaining phrase
    

    如何“ 不是 MSWinEventLog 正则表达式组中的'' ([\w\/\.\-]*) ?

    注:
    上面的第二个短语应该返回“not matched”

    2 回复  |  直到 15 年前
        1
  •  8
  •   VonC    15 年前
    <(\d+)>(\w+\s\d+\s\d+(?::\d+){2})\s(?!MSWinEventLog)([\w\/\.\-]*)(.*)
    

    negative lookahead (这里: (?!MSWinEventLog) ')应该足够了:

    消极的展望是必不可少的,如果你 想要匹配的东西后面跟不上别的东西 .
    在解释字符类时,我已经解释了为什么不能使用否定的 character class 匹配“q”而不是“u”。负面展望提供了解决方案: q(?!u) .

        2
  •  1
  •   Etaoin    15 年前

    你可以用消极的展望来做:

    <(\d+)>(\w+\s\d+\s\d+(?::\d+){2})\s(?!MSWinEventLog)([\w\/.-])(.)
                                       -----------------
    

    (?!MSWinEventLog) 只有不匹配才匹配 紧接着 匹配“mswineventlog”的表达式。