Regex for Matching All Strings That Contain Two Different Words from a List


February 2019


12 time


I have need for a regular expression (in Java) that matches a string if and only if it contains two different words from a given list.

For example, if the list of words is {blue,yellow,pink}, then the strings "blue and pink" and "yellow is the new blue" will match, but the strings "I like blue" will not (only one word from the list appears) and neither will the string "My pink shirt is so very pink" (it does not contain two or more different words, but the same word twice).

The closest I could get to my desired regex is:


This regex will match any string that contains two or more words from the list, but it will do so even if the two words are the same (as in the "My pink shirt is so very pink" example).


0 answers