Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex to validate the comma or space separated values with limit

I am looking for a regex to validate the comma/space separated string (Allowing Alphanumeric and underscore) with the limit in each values to 64 and no of such values to 16.

var1,val2, val_3 val4  - valid
val*1, val&2 - Invalid due to illegal character
val1...65,val2, val3 val4 - invalid due to first value has 65 characters
val1,val2, val3 val4,...,val17 - invalid because no of values as more than 16

I have created a partial regex but there is some issue which I am not able to figure out.

^([0-9a-zA-Z_]{0,64}){1}(([,\s]+)([0-9a-zA-Z_]{0-64})){0,15}$

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This part [0-9a-zA-Z_]{0,64} of the pattern can also match 0 times so it could also match an empty string.

You can omit {1} from the pattern, the notation in the second quantifier should be {0,64} instead of {0-64}

To get a match only, you can omit all the capture groups, and use a single repeating non capture group.

You might write the pattern as:

^\w{1,64}(?:[, \t]+\w{1,64}){0,15}$
  • ^ Start of string
  • \w{1,64} Match 1-64 word characters
  • (?: Non capture group
    • [, \t]+ Match either a comma, space or tab (or use [,\s]+)
    • \w{1,64} Match 1-64 word characters
  • ){0,15} Close the non capture group and repeat 0 – 15 times
  • $ End of string

Regex demo

Note that \s can also match a newline, so you could also use [,\s]+

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading