Regex, valid if there are specific words in any order

Asked

Viewed 170 times

2

For me it is always better to exemplify the cases of regex. Look at this:

  • Palavra1- Valid
  • Word2- Valid
  • Palavra1 Word2- Valid
  • Word2 Palavra1- Valid
  • Palavra1 Palavra1- Invalidity
  • Word2 Word2- Invalidity

But say it’s 5 or 6 words, it’s very expensive to write ALL possibilities

1 answer

3

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

You can use a regex like this:

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

She seeks a word \b(\w+) followed by a space \s (to make sure that another word will come), and then search the string for a repetition of what was captured in the previous with \1.

example of regex: https://regex101.com/r/nQ8bW7/1

jsFiddle: https://jsfiddle.net/28fmmrna/

  • 1

    Ok! Well I didn’t know that 1 , well, there it is easy, first I check if it only contains the allowed words, then I check if there is no repetition !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.