-1

I am using regex to assert that my string is a combination of a maximum of 4 numbers separated by commas, the numbers must be between 1 and 4. Examples of valid strings would be :

1,2,3
1,2
1
1,2,3,4
4,1

To achieve this i am using ^[1-4](,[1-4])*$, but i am not able to limit the number of characters on the string. so in my implementation the following string is also valid 1,2,3,4,2,3 which is against what i am trying to achieve.

Purple Haze
  • 530
  • 7
  • 22

3 Answers3

1

You can try this:

^[1-4](,[1-4]){0,3}$
Oliver Hao
  • 715
  • 3
  • 5
  • 2
    Or better discard the groups and just check whether its matching by using `^[1-4](?:,[1-4]){0,3}$` regex [`here`](https://regex101.com/r/tiQwf8/1) – Kunal Mukherjee Jul 25 '19 at 09:42
0

this should do:

^[1-4](,[1-4]{1}){0,3}$
IWHKYB
  • 481
  • 3
  • 11
0

Here is your regex : ^[1-4](,[1-4]){0,3}$. You can test it here.

Hadrien K.
  • 161
  • 1
  • 14