Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding words in any order with regex

Tags:

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?

like image 348
Daniel Silva Avatar asked Aug 01 '15 00:08

Daniel Silva


1 Answers

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)

like image 155
Alex Netkachov Avatar answered Sep 28 '22 07:09

Alex Netkachov