Search code examples
regexgrep

Regular expression to match specific words seperated by spaces


I have a list of say 5 words (foo bar foobar footable somebar). This list of words will be provided as a string each separated by space and in any order. I need a regex matching below requirements

  1. inputted string should contain only the 5 above mentioned words
  2. each word separated by space
  3. each word only once
  4. regex should match the entire string - if any portion does not match above criteria, it should be failed match

So far I have this (\b(foo|bar|foobar|footable|somebar)\b\ *){1,5}

  1. Matches only the mentioned words
  2. Words separated by space

Need a solution for the 3rd & 4th requirements

  1. each word only once
  2. regex should match the entire string - if any portion of the string does not match above criteria, it should be a failed match

Solution

  • Start with a regular expression that matches exactly 5 words:

    ^(?:\w+\s+){4}\w+$
    

    The anchors ensure that this matches the entire string.

    Then prefix this with lookaheads that match each of the words.

    (?=.*\bfoo\b)(?=.*\bbar\b)(?=.*\bfoobar\b)(?=.*\bfootable\b)(?=.*\bsomebar\b)^(?:\w+\s+){4}\w+$
    

    DEMO