在JavaScript中匹配一个单词而没有另一个单词的正则表达式

时间:2014-10-19 17:30:13

标签: javascript regex

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

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

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

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

3 个答案:

答案 0 :(得分:3)

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

^(?=(?:(?!\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)

答案 1 :(得分:2)

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

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"
}

答案 2 :(得分:1)

这应该适合你:

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?