2015-05-02 57 views
3

我使用正則表達式負前瞻總是返回true

/(?!results)/i 

據我瞭解,它會匹配不包含單詞「結果」的字符串。但是,當我嘗試

/(?!results)/i.test('basketball results') 

它返回true。如何匹配不包含單詞results的字符串?

回答

4

這個正則表達式匹配每一個後面沒有results的位置。見demo

要匹配一個不包含results的表達式,您需要使用^(?!.*results.*$).*。見another demo

1

您可以使用簡單的indexOf在這裏檢查。它將返回-1是子串不包含在字符串中,否則爲零或更大:

"basketball results".indexOf('results') == -1