Maven Maven - 29 days ago 12
C# Question

Regex for integers delimited by commas

I need a

Regex
that only allows Integers (positive and negative) delimited by comma
2,-3,4
, but the comma should only be in the middle of two integers, not at the start or end or two consecutive commas like
23,34,,4
.

Currently I have this:

Regex regex = new Regex(@"^\d{1,10}([,]\d{10})*$");
if (!regex.IsMatch("123,34,2,34,234"))


But it doesn't seems to match any thing it even rejects valid inputs like
123,34,2,34,234


Can you please point out what is wrong with my above regex.

Answer

The \d{10} subpattern only matches 10-digit chunks.

You need to allow 1 to 10 with {1,10} (or 1 and more with +) with

@"^\d{1,10}(?:,\d{1,10})*$"

or

@"^\d+(?:,\d+)*$"

Note the use of a non-capturing group (?:...) that does not store the submatches, and is only meant to group a sequence of subpatterns.

See the regex demo

EDIT: To allow matching negative values, add an optional -:

@"^-?\d+(?:,-?\d+)*$"
   ^^       ^^  

See another regex demo.