【问题标题】:Regex that matches one word without another in JavaScript在 JavaScript 中匹配一个单词而不匹配另一个单词的正则表达式
【发布时间】:2023-04-01 07:43:01
【问题描述】:

我想匹配包含字符串yes 的表达式,但前提是它前面没有字符串no

例如,这与匹配: Hello world, major yes here!
但这不匹配:Hell no yes

第二个字符串不匹配,因为yes 字符串前面有no 字符串。显然这需要否定的lookbehind,它没有在JavaScript regex 风格中实现,我尝试过这样的东西: /((?!no ))yes/
/^(?!.*no) yes$/

但它们似乎没有达到预期的效果:/

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    我认为这里不需要正则表达式。你可以这样做

    var str = "Hell no yes", match = null, no = str.indexOf("no"), yes = str.indexOf("yes");
    if(no >= 0 && (yes < 0 || no < yes)) { // check that no doesn't exist before yes
       match = str.match(/yes/)[0]; // then match the "yes"
    }
    

    【讨论】:

    • +1 用于使用简单的代码而不是凌乱的正则表达式破解。可能必须确保“否”出现在“是”之前。
    • 这是一个绝妙的解决方案,但解决了另一个问题。我有一系列针对不同情况的正则表达式——比这个更复杂。而且我不想为我可能拥有的每个字符串案例实现流逻辑 - 这就是发明正则表达式的目的。
    • @MeLight - 所以只需创建一个传递两个单词的函数,就可以在任何地方重用相同的代码。
    • @MeLight 那么你真的必须创建一个更混乱的正则表达式并且也相当复杂
    • 如果str 不包含no (indexOf() = -1),此语句将失败。所以它需要额外的条件
    【解决方案2】:

    你可以试试下面的正则表达式。

    ^(?=(?:(?!\bno\b).)*yes).*
    

    DEMO

    说明:

    ^                        the beginning of the string
    (?=                      look ahead to see if there is:
      (?:                      group, but do not capture (0 or more
                               times):
        (?!                      look ahead to see if there is not:
          \b                       the boundary between a word char
                                   (\w) and something that is not a
                                   word char
          no                       'no'
          \b                       the boundary between a word char
                                   (\w) and something that is not a
                                   word char
        )                        end of look-ahead
        .                        any character except \n
      )*                       end of grouping
      yes                      'yes'
    )                        end of look-ahead
    .*                       any character except \n (0 or more times)
    

    【讨论】:

      【解决方案3】:

      这应该适合你:

      var reg = /^((?!no).)*yes.*$/
      
      console.log("Test some no and yes".match(reg))
      console.log("Test some yes".match(reg))
      console.log("Test some yes and no".match(reg))
      

      请注意,它不会在没有“是”字的句子中起作用:

      console.log("Test some without".match(reg))
      

      以下是可能对问题有更多帮助的参考:

      Regular expression to match string not containing a word?

      【讨论】:

      • 没关系。我只是想提供另一个(也许更简单)的解决方案:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-23
      相关资源
      最近更新 更多