tags:

views:

159

answers:

3

This is something of a follow up from a previous question. The requirements have changed, and I'm looking for some help with coming up with regex for either a comma separated number or a number with no commas. Sample input is below, along with some failed attempts.

Any help is appreciated.

Acceptable input:

1,234,567
1234567

Unacceptable input:

1234,567
1,234567

Some failed attempts:

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

Original success:

^\d{1,3}(?:[,]\d{3})*$
+3  A: 

Just add an "or one or more digits" to the end:

^(?:\d{1,3}(?:[,]\d{3})*|\d+)$

I think you had it almost right the first time and just didn't match up all your parentheses correctly.

Rich
A: 

Try this:

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

This will match any sequence that begins with one to three digits, followed by either

  • one or more segments of a comma followed by three digits, or
  • zero or more digits.
Gumbo
+1  A: 

Why not use Int.TryParse() rathern then a regex?

Ian Ringrose