I\'m trying to build a search feature for a project which narrows down items based on a user search input and if it matches the keywords listed against items. For this, I\'m
You can achieve this will lookahead assertions
^(?=.*\bmeat\b)(?=.*\bpasta\b)(?=.*\bdinner\b).+
See it here on Regexr
(?=.*\bmeat\b)
is a positive lookahead assertion, that ensures that \bmeat\b
is somewhere in the string. Same for the other keywords and the .+
is then actually matching the whole string, but only if the assertions are true.
But it will match also on "dinner meat Foobar pasta"
your regex looks pretty good:
\b(meat|pasta|dinner)\b
Check that the length of matches equals the number of keywords (in this case, three):
string.match(re).length === numberOfKeywords
where re
is the regex with a g
flag, string
is the data and numberOfKeywords
is the number of keywords
This assumes that there are no repeated keywords.
Based on the accepted answer I wrote a simple Java method that builds the regex from an array of keywords
public static String regexIfAllKeywordsExists(String[] keywords) {
StringBuilder sb = new StringBuilder("^");
for (String keyword : keywords) {
sb.append("(?=.*\\b");
sb.append(keyword);
sb.append("\\b)");
}
sb.append(".+");
return sb.toString();
}