I have a requirement to find a specific word AND any words from a list. So far I have this:
^.*?(apple)(?:\W+\w+){0,30}?\W+(ipad|itunes).*
This matches "apple" and either "ipad" or "itunes".
This fails however if "ipad" or "itunes" is before "apple".
Can anyone advise?
You should better use lookahead for that:
/^(?=.*?\bapple\b)(?=.*?\b(ipad|itunes)\b).*$/i
Update: As per this comment from OP: Can you advise how my word limit would fit in here? eg I must find any from the list within 20 words of apple?
Can you advise how my word limit would fit in here? eg I must find any from the list within 20 words of apple?
/^(?=.*?\bapple\b)(?=.*?\bapple(\W+\w+){0,20}\b(ipad|itunes)\b).*$/i
Doesn't the simple version work ( 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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.