Search code examples
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:

    • (?=.*NCAA): Positive lookahead to assert presence of string NCAA any where ahead of the current position
    • (?=.*Basketball): Positive lookahead to assert presence of string Basketball any where ahead of the current position

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

    NCAA.*?Basketball|Basketball.*?NCAA