Maven Maven - 1 year ago 92
C# Question

Regex for integers delimited by commas

I need a

that only allows Integers (positive and negative) delimited by comma
, but the comma should only be in the middle of two integers, not at the start or end or two consecutive commas like

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

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

Answer Source

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




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 -:

   ^^       ^^  

See another regex demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download