【问题标题】:Negative lookbehind to escape @@ in javascript在javascript中转义@@的负向回溯
【发布时间】:2016-11-29 16:33:23
【问题描述】:

我正在考虑如何创建一个仅当它不与另一个 @ 匹配时才匹配 @test 的正则表达式。我有一个消极的后视解决方案,但 JS 不支持该功能。是否有没有负面回顾的解决方案? Ex. This @test should be a match. This @@test should not be a match.

【问题讨论】:

  • 你想用其他东西替换匹配的文本吗?

标签: javascript regex


【解决方案1】:

即使@test 位于字符串的开头,也可以使用以下方法:

(?:^|[^@])@test

Regex101

【讨论】:

    【解决方案2】:

    您可以在@test 之前使用否定字符组来排除:

    /[^@]@test/
    

    这不适用于行首,但适用于您的示例文本。如果您也需要担心行首,您可以这样做:

    /(^|[^@])@test/
    

    这将匹配@test 作为该行中的第一件事,或者匹配@test 前面有一些非@ 字符。

    【讨论】:

      【解决方案3】:

      否定字符类呢?

      /(?:[^@]|^)@test/
      
      • [^@] 匹配除 @ 以外的任何内容

      示例

      "This @@test should not be a match".match(/(?:[^@]|^)@test/)
      // null
      "This @test should not be a match".match(/(?:[^@]|^)@test/)
      // [" @test"]
      

      【讨论】:

      • 只要该行不以@test开头。
      • @SunnyPatel 我已经编辑了答案。希望现在没事
      • 后视必须是固定的字符长度。 0 和 1 的长度不起作用。
      • @SunnyPatel 对不起,我没有得到你。正则表达式中没有后面的内容。而且javascript不支持lookbehinds
      猜你喜欢
      • 1970-01-01
      • 2018-03-22
      • 2015-07-12
      • 2012-03-03
      • 2016-02-04
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多