1

^(all|contact|all,contact|contact,all)$

do not allow all,all or contact,contact or all,contact,all, etc.

I need to be able to have an equivalent pattern, but I want to reduce because I may have more elements in the future and finding all possible combinations would be difficult.

eg with 3 elements ^(all|contact|another|all,contact|contact,all|all,another|another,all|all,another,contact|all,contact,another|contact,all,another|contact,another,all|another,all,contact|another,contact,all)$

It should accept one word or multiple words separated by commas and each word only appears once. Thanks for the help in advanced.

3

2 Answers 2

2

A bit un-regexlike, but would it not be easier and possibly more performant to just split() on the , character and check for uniqueness on the resulting array?

This would arguably be more robust and easier to maintain, especially if you have a heavily minimised/difficult to read regular expression to begin with and wanted to add more words.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the suggestion but it didn't answer the question.
1

You may use

 /^(?!.*\b(\w+)\b.*\b\1\b)(?:another|contact|all)(?:,(?:another|contact|all))*$/

See the regex demo.

Details

  • ^ - start of the string
  • (?!.*\b(\w+)\b.*\b\1\b) - a negative lookahead that fails the match if, immediately after any 0+ chars other than line break chars there is a whole word that also occurs after another chunk of any 0+ chars other than line break chars
  • (?:another|contact|all) - one of the three alternatives
  • (?:,(?:another|contact|all))* - any 0+ repetitions of:
    • , - a comma
    • (?:another|contact|all) - one of the three alternatives
  • $ - end of string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.