Home > Blockchain >  Regex to validate the comma or space separated values with limit
Regex to validate the comma or space separated values with limit

Time:02-02

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}$

CodePudding user response:

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]

  •  Tags:  
  • Related