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

前端 未结 3 1737
萌比男神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: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();
    }
    

提交回复
热议问题