2

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})*$
Community
  • 1
  • 1
CodeMonkey1313
  • 14,477
  • 17
  • 71
  • 109

5 Answers5

4

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
  • 34,878
  • 31
  • 108
  • 151
2

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
  • 594,236
  • 102
  • 740
  • 814
  • +1 for correctly dealing with the right number of comma groups. Look [here](http://stackoverflow.com/questions/4246077/simple-problem-with-regular-expression-only-digits-and-commas/4247184#4247184) for a broader discussion and elaboration. – tchrist Nov 23 '10 at 14:49
1

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

Ian Ringrose
  • 49,271
  • 50
  • 203
  • 302
0

Please see this answer for a definitive treatment of the β€œIs it a number?” question, including allowance for correctly comma-separated digit groups.

Community
  • 1
  • 1
tchrist
  • 74,913
  • 28
  • 118
  • 169
0

One thing i've noticed with all these is that the first bit of the regex allows for '0' based numbers to work. For example the number:

0,123,456

Would match using the accepted answer. I've been using:

((?<!\w)[+-]?[1-9][0-9]{,2}(?:,[0-9]{3})+)

Which also ensures that the number has nothing in front of it. It does not catch numbers of less then 1,000 however. This was to prevent ill-formatted numbers from being captured at all. If the final + were a ? the following numbers would be captured:

0,123
1,2 (as 2 separate numbers)

I have a strange set of numbers to match for (integers with commas, with spaces and without both), so i'm using pretty restrictive regexs to capture these groups.

Anyway, something to think about!

Jos
  • 19
  • 3