2010-07-20 46 views
1

下面的正則表達式是錯誤的 - 有人可以幫助找到所有:-)沒有「請忽略我」在前面? 我以前沒有需要這樣的正則表達式。詞邊界可能會混淆事物。
感謝Negative look-around

<script type="text/javascript"> 
function regexTest(string, assert) { 
    document.write('<hr>') 
    document.write(string) 
    document.write("[") 
    document.write(string.match(/\b((?!please ignore me)\:\-\))\b/gi)!=null); 
    document.write("]?" + assert); 
} 

regexTest("1. this is the first string :-)  ",true); 
regexTest("2. :-)",true) 
regexTest("3. another string:-)here",true); 
regexTest("4. Ending a sentence with :-)",true); 
regexTest("5. please ignore me :-)",false); 
</script> 
+0

看看這個http://stackoverflow.com/questions/2973436/regex-lookahead-lookbehind-and-atomic-groups/2973609#2973609 – Amarghosh 2010-07-20 09:34:43

回答

9

如果你想匹配:-)通過「請忽略我」開頭,那麼你需要一個負回顧後(?<!...)代替先行(?!...)。但是,JavaScript不支持向後看。

所以你可以做的是匹配(\bplease ignore me\s*)?:-\)然後,如果匹配,檢查捕獲組$1是否爲空。

+0

+1我只是寫這個,但你打敗了我! – 2010-07-20 09:21:53

+0

謝謝 - 非常聰明 – mplungjan 2010-07-20 09:46:10