-4

I have a scenario that, a string should accept only numbers and comma, In between comma the number should be in range of 0 to 999.

Valid case:

322,333,459,999,000,001

Invalid case:

32222,44444444444,666666,

I tried with this regular expression [0-9{3},/,]+. It only allows comma and numbers.

But how can we restrict to 3 digits in between the comma.

Thanks in advance.

naurel
  • 605
  • 4
  • 17
Sairam
  • 169
  • 12
  • Isn't `[\d{3},]+` enough ? I don't know why you've put `/` in your regex. – naurel Oct 31 '19 at 14:57
  • @naurel not really, unless you want to allow the following characters: digits, `{`, `3`, `}`, `,`. The square brackets denote a character class, so only the *characters* within are allowed. Most of the symbols that have special meaning in regex loose it in there. – VLAZ Oct 31 '19 at 15:02
  • `(?:\d{3}|,)+` might be better. – naurel Oct 31 '19 at 15:04
  • @naurel `"100,200,300,"` passes now. Also `","` or `",,,,,,,,,,,,,,,,,,,,"` and `"100200300"` – VLAZ Oct 31 '19 at 15:10

2 Answers2

0

This should work:

^\d{3}(,\d{3})*$


^ : beginning of line

\d : digit

{3}: 3 times

* : 0 or more times

$ : end of line


EDIT:

In case you do not plan to reuse the group (expression between parantheses) you can make it non-capturing with ?:. It will look like that:

^\d{3}(?:,\d{3})*$

ieggel
  • 415
  • 1
  • 9
0

What you're looking for :

^(?:\d{1,3},)*\d{1,3}$

To awnser your exact question .{1,3} means that you want any character to be present between 1 and 3 times. This way you limit occurrences.

naurel
  • 605
  • 4
  • 17