Regex, valid if there are specific words in any order

Posted on

Question :

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

    

Answer :

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[sw]*

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

    

Leave a Reply

Your email address will not be published. Required fields are marked *