4

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

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • 2
    post input and expected output – vks Oct 07 '14 at 14:32
  • This is a duplicate of http://stackoverflow.com/questions/13911053/regular-expression-to-match-all-words-in-a-query-in-any-order – jmar777 Oct 07 '14 at 14:36
  • not, it`s actually not a duplicate, i need to have only these words and nothing more in the string. Sorry, if i forgot to mention. Well "one;two;three", "three;two;one" "threetwoone" should be matched "one;two;four;three","one;one;two;three" - should not be matched – user3414347 Oct 07 '14 at 14:40

2 Answers2

6

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

Community
  • 1
  • 1
Jonny 5
  • 12,171
  • 2
  • 25
  • 42
1
(one|two|three);?(?!\1)(one|two|three);?(?!\2)(one|two|three)

Try this.See demo.

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

vks
  • 67,027
  • 10
  • 91
  • 124