John Bench
John Bench

Reputation: 35

regexp javascript simplify

^(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.

Upvotes: 1

Views: 73

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

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.

Upvotes: 1

user9456025
user9456025

Reputation:

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.

Upvotes: 2

Related Questions