2010-07-20 78 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