Regular Expression to MATCH ALL words in a query, in any order

前端 未结 3 1738
萌比男神i
萌比男神i 2020-12-01 13:51

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

相关标签:
3条回答
  • 2020-12-01 14:22

    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"

    0 讨论(0)
  • 2020-12-01 14:22

    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.

    0 讨论(0)
  • 2020-12-01 14:24

    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();
    }
    
    0 讨论(0)
提交回复
热议问题