有没有办法使用正则表达式匹配不包含另一个字符串的字符串?

rye*_*guy 1 regex

是否可以使用正则表达式来创建匹配不包含某个字符串的片段的模式?

这个神奇的正则表达式会接受这个输入并检查括号之间的什么: (foo bar) (barfoo) (zab) (foozab)并且只返回,zab因为它不包含foo在括号之间.

这是可能的,还是我应该只捕获括号之间的所有内容并使用langauge函数来排除它们?

Lil*_*ard 7

根据引擎的不同,您可以使用先行断言.

\(((?:(?!foo)[^)])+)\)
Run Code Online (Sandbox Code Playgroud)

该正则表达式将匹配带括号的字符串,其中字符串内的字符不匹配子表达式"foo"(在这种情况下只是一个字符串).

这是扩展形式:

\(          # match the opening (
  (         # capture the text inside the parens
   (?:      # we need another group, but don't capture it
    (?!foo) # fail if the sub-expression "foo" matches at this point
    [^)]    # match a non-paren character
   )+       # repeat that group
  )         # end the capture
\)          # end the parens
Run Code Online (Sandbox Code Playgroud)