Daniel Silva
Daniel Silva

Reputation: 331

Finding words in any order with regex

Considering this entries...

red yellow green
yellow green red
green red yellow 
other red yellow 
other green red

I can match red, yellow, green in any order (first 3 lines) with:

^(^red|^yellow|^green) (red|yellow|green) (red$|yellow$|green$)$

Note that i need to find exactly this words, nothing else. But when i have more words the expression grows a lot.

e.g. (with 4 words)

^(^red|^yellow|^green|^black) (red|yellow|green|black) (red|yellow|green|black) (red$|yellow$|green$|black$)$

My question is: is there any other simpler way to do this with regex?

Upvotes: 6

Views: 155

Answers (1)

Alex Netkachov
Alex Netkachov

Reputation: 13522

If you can tolerate red red yellow (well, I think you can as your regexps match lines like this) then the regexp you need is

^(red|yellow|green)( (red|yellow|green))*$

You can test it there: https://regex101.com/r/fC3pM3/1 (it also has nice explanation)

Upvotes: 3

Related Questions