簡體   English   中英

正則表達式在JavaScript中匹配一個單詞而沒有另一個單詞

[英]Regex that matches one word without another in JavaScript

我想匹配和包含字符串yes表達式,但前提yes它不以字符串no開頭。

例如,此匹配項: Hello world, major yes here!
但這不匹配: Hell no yes

第二個字符串不匹配,因為yes字符串后面是no字符串。 顯然,這需要在后面進行否定,這不是在JavaScript正則表達式中實現的,我已經嘗試過類似的東西: /((?!no ))yes/
/^(?!.*no) yes$/

但它們似乎沒有達到預期的效果:/

您可以嘗試以下正則表達式。

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

演示

說明:

^                        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)

我認為這里不需要正則表達式。 你可以這樣子做

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

這應該為您工作:

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))

請注意,它在沒有“ yes”這樣的單詞的句子中不起作用:

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

這是可能對問題有更多幫助的參考:

正則表達式匹配不包含單詞的字符串?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM