2014-10-19 36 views
1

我想匹配和包含字符串yes的表達式,但前提是前面沒有字符串no在JavaScript中匹配一個單詞而沒有另一個單詞的正則表達式

例如,這與比賽: Hello world, major yes here!
但這將不會匹配:Hell no yes

第二個字符串不匹配,因爲yes字符串由no字符串開頭。顯然,這需要否定的回顧後,這是不是在JavaScript正則表達式的味道實現,我已經試過類似的東西: /((?!no))yes/
/^(?!.*no) yes$/

,但他們似乎並沒有收到預期的效果:/

回答

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

這工作,謝謝 – MeLight 2014-10-19 17:40:27

+0

不客氣.. – 2014-10-19 17:42:46

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

+1使用簡單的代碼,而不是凌亂的正則表達式的黑客。可能必須確保「否」在「是」之前出現。 – jfriend00 2014-10-19 17:34:42

+0

這是一個很好的解決方案,但是解決了另一個問題。對於不同的情況,我有一系列的正則表達式 - 比這個更復雜。我不想爲每個可能有的字符串情況實現流程邏輯 - 這正是發明的正則表達式。 – MeLight 2014-10-19 17:37:46

+0

@ jfriend00謝謝你的建議。 – 2014-10-19 17:39:06

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?

+1

這工作也很好!但我已經接受了一個答案。 +1 – MeLight 2014-10-19 17:52:06

+1

它確定。我只是想給另一個(也許更簡單)解決方案:) – DRAX 2014-10-19 17:53:23

相關問題