2012-08-22 116 views
7

在下面的例子的輸出是真實的。它cookie,它也符合cookie14214我猜這是因爲cookie是字符串cookie14214英寸我該如何磨練​​這場比賽才能獲得cookieJavaScript的正則表達式不匹配確切字符串

var patt1=new RegExp(/(biscuit|cookie)/i); 
document.write(patt1.test("cookie14214")); 

這是最好的解決方案嗎?

var patt1=new RegExp(/(^biscuit$|^cookie$)/i); 

回答

5

問題的答案取決於你周圍的字cookie字符的津貼。如果字是要嚴格出現在單獨一行,則:如果你想允許符號(空格,.,等),而不是字母數字值,你可以試試

var patt1=new RegExp(/^(biscuit|cookie)$/i); 

var patt1=new RegExp(/(?:^|[^\w])(biscuit|cookie)(?:[^\w]|$)/i); 

二正則表達式,解釋說:

(?:     # non-matching group 
    ^    # beginning-of-string 
    | [^\w]   # OR, non-alphanumeric characters 
) 

(biscuit|cookie) # match desired text/words 

(?:     # non-matching group 
    [^\w]   # non-alphanumeric characters 
    | $    # OR, end-of-string 
) 
+0

你測試嗎?我不認爲你可以在所需的字符串後面使用負向預覽。 – jbabey

+0

@ jbabey是的,用螢火蟲測試過;另外,正則表達式不使用任何lookahead(正數或負數)。第二個是使用非匹配組,'(?:?!',如果這是你與'混淆什麼(' – newfurniturey

+0

我從來沒有見過這種語法之前,好知道 – jbabey

2

是或使用詞邊界。請注意,這將匹配great cookies而不是greatcookies

var patt1=new RegExp(/(\bbiscuit\b|\bcookie\b)/i); 

如果你想確切的字符串匹配cookie,那麼你甚至不需要正則表達式,只是用==,因爲/^cookie$/i.test(s)是基本相同s.toLowerCase() == "cookie"

+0

+1,儘管使用的''==代替''===:P – jbabey

相關問題