Is there a regular expression for a comma-separated list of discrete values?

I use the following regular expression to check a list of values ​​separated by commas.

^Dog|Cat|Bird|Mouse(, (Dog|Cat|Bird|Mouse))*$

Values ​​are also listed in the drop-down list in the Excel cell check, so the user can select one value from the drop-down list or enter several values ​​separated by commas.

A regular expression does a good job of preventing the user from entering anything other than the approved values, but this does not stop the user from entering duplicates. For example, the user can enter “Dog” and “Dog, Cat”, but the user can also enter “Dog, Dog”.

Is there a way to prevent duplication using a single regex? In other words, I need to be able to apply a discrete list of approved values, separated by commas.

Thanks!

+5
source share
2 answers

Use the backlink and negative view:

^(Dog|Cat|Bird|Mouse)(, (?!\1)(Dog|Cat|Bird|Mouse))*$

EDIT . This will not work with cases like "Cat, Dog, Dog" ... You will need to create a hybrid solution for such cases - I do not believe there is one regular expression that can handle this.


Here is another method. You need to check two things, firstly, that it matches this:

(?:(?:^|, )(Dog|Cat|Bird|Mouse))+$

(This is a slightly shorter version of the original regex)

, :

(Dog|Cat|Bird|Mouse).+?\1

.

var valid = string.match( /(?:(?:^|, )(Dog|Cat|Bird|Mouse))+$/ ) &&
           !string.match( /(Dog|Cat|Bird|Mouse).+?\1/ );
+10

J-P, , . - :

var valid = string.match( /(?:(?:^|, )([a-z]*))+$/ ) &&
    !string.match( /([a-z]*).+?\1/ );

, . .;)

.

0

All Articles