2013-10-31 188 views
1

我有一個要求來查找特定的單詞和列表中的任何單詞。到目前爲止,我有這個:Javascript正則表達式 - 包含任意順序的單詞和單詞

^.*?(apple)(?:\W+\w+){0,30}?\W+(ipad|itunes).* 

這匹配「蘋果」和「ipad」或「itunes」。

但是,如果「ipad」或「itunes」位於「apple」之前,則會失敗。

任何人都可以建議嗎?

回答

1

你應該更好地利用前瞻爲:

/^(?=.*?\bapple\b)(?=.*?\b(ipad|itunes)\b).*$/i 

更新:按照從OP此評論:Can you advise how my word limit would fit in here? e.g. I must find any from the list within 20 words of apple?

/^(?=.*?\bapple\b)(?=.*?\bapple(\W+\w+){0,20}\b(ipad|itunes)\b).*$/i 
+1

好東西!非常感謝。 – Ben

+0

不客氣,很高興它爲你解決。 – anubhava

+0

你能告訴我這個詞限制怎麼適合這裏嗎?例如我必須在20字以內的蘋果列表中找到任何內容? – Ben

0

並不簡單的版本工作(http://jsfiddle.net/xhdBQ/1/)?

var list = ["ipad", "itunes"]; 
var word = "apple"; 
list.push(word) 

var regex = new RegExp("(" + list.join("|") + ")", "g"); 
console.log(regex); 
console.log("blabla...apple,,safsd ssdfipadaad itunes".match(regex)) 
相關問題