regexstringfindany

Java Regex looking a combination of words in any order


I'm looking for a way to find two or more words in a sentence that might come in any order. For example I might look for the words "NCAA" and "Basketball" in a sentence that says NCAA Indiana Vs. Purdue Basketball" or it might say "Indiana Vs. Purdue Basketball NCAA". How would I write the regex for the words showing in any order and any location in the string?


Solution

  • You can use lookahead:

    (?=.*NCAA)(?=.*Basketball)
    

    Explanation:

    Or else use alternation if your regex tool doesn't support lookaheads:

    NCAA.*?Basketball|Basketball.*?NCAA