[英]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.