Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression "all three in any order and nothing more"

Tags:

regex

I need to make a reg expression that will match following conditions:

1) mathing only if it has three words 2) not separated or separated by semicolon (;) 3) in any order 4) all of words should be included, otherwise it will not match

I tried this one:

^(?=(.*;|)one)(?=(.*;|)two)(?=(.*;|)three).*$

but somehow it mathes variants like oneasfafasfsaf;two;three it`s wrong

please, help!

P.S. sometimes it`s needed to have more than three, but i want to understand the core

like image 958
user3414347 Avatar asked Sep 14 '25 10:09

user3414347


2 Answers

You could capture all 3 and check for each exists, then, if string is only composed of the 3 words:

^(?=.*?(one))(?=.*?(two))(?=.*?(three))(?:(?:\1|\2|\3);?){3}$

See test at regex101.com (explanation on the right); Regex FAQ

like image 174
Jonny 5 Avatar answered Sep 16 '25 07:09

Jonny 5


(one|two|three);?(?!\1)(one|two|three);?(?!\2)(one|two|three)

Try this.See demo.

http://regex101.com/r/hQ1rP0/41

like image 43
vks Avatar answered Sep 16 '25 08:09

vks