具有负前瞻性的Regex仍然匹配

  • 本文关键字:Regex 前瞻性 regex
  • 更新时间 :
  • 英文 :


我正在尝试测试一个shebang"#!",看看它是否两边都没有使用此regex (?!/)#!(?!/) 的正斜杠

它应该匹配:#!z#!#!zz#!z

它应该匹配:/#!#!//#!/

我在shebang周围放了否定的lookahead,这样它就不会匹配任何斜杠,事实上它也不会匹配尾随斜杠,但出于某种原因,它仍然匹配前导斜杠/#!

regexr上的示例

有什么关于为什么会发生这种情况/如何解决的想法吗?

您希望使用负向后看反向向前看

(?<!/)#!(?!/)

解释

(?<!     # look behind to see if there is not:
  /      #   '/'
)        # end of look-behind
#!       # '#!'
(?!      # look ahead to see if there is not:
  /      #   '/'
)        # end of look-ahead

最新更新