我有一个要求来查找特定的单词和列表中的任何单词。到目前为止,我有这个:Javascript正则表达式 - 包含任意顺序的单词和单词
^.*?(apple)(?:\W+\w+){0,30}?\W+(ipad|itunes).*
这匹配“苹果”和“ipad”或“itunes”。
但是,如果“ipad”或“itunes”位于“apple”之前,则会失败。
任何人都可以建议吗?
我有一个要求来查找特定的单词和列表中的任何单词。到目前为止,我有这个:Javascript正则表达式 - 包含任意顺序的单词和单词
^.*?(apple)(?:\W+\w+){0,30}?\W+(ipad|itunes).*
这匹配“苹果”和“ipad”或“itunes”。
但是,如果“ipad”或“itunes”位于“apple”之前,则会失败。
任何人都可以建议吗?
你应该更好地利用前瞻为:
/^(?=.*?\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
并不简单的版本工作(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))
好东西!非常感谢。 – Ben
不客气,很高兴它为你解决。 – anubhava
你能告诉我这个词限制怎么适合这里吗?例如我必须在20字以内的苹果列表中找到任何内容? – Ben