Regex, valid if there are specific words in any order

3

For me it is always better to exemplify regex cases. See:

  • Word1 - Valid
  • Word2 - Valid
  • Word1 Word2 - Valid
  • Word2 Word1 - Valid
  • Word1 Word1 - Invalid
  • Word2 Word2 - Invalid

But let's say 5 or 6 words, it is very costly to write ALL the possibilities

    
asked by anonymous 30.04.2016 / 20:47

1 answer

4

It is difficult with regex to know if there is a sequence without repetitions, but it is easy to know if there is a repetition of words. Using a capturing group you can check if a given word returns to the string.

You can use a regex like this:

 \b(\w+)\s[\s\w]*

It looks for a word \b(\w+) followed by a space \s (to be sure another word will come), and then searches the string for a repeat of what was previously caught with .

regex example: link

jsFiddle: link

    
30.04.2016 / 21:24