tags:

views:

50

answers:

2

What is a regex that can match a generally understandable number? (the simpler the better)

for example, it should match:

10
10.0
10.00
3.3333
123456
100,000
1,234,567
33,456.22
-2.2
.2
-.2
+.2
0.2
.20

should not match:

33,33.1
1.2.3
100,000,000000
+1  A: 
^[+-]?(?:\d+|\d{1,3}(?:,\d{3})+|(?:\d*|\d{1,3}(?:,\d{3})+)\.\d+)$

should catch most cases.

Explanation:

^                      # start of string
[+-]?                  # optional sign
(?:                    # match either...

 \d+                   # only digits
 |                     # or

 \d{1,3}(?:,\d{3})+    # only comma-separated digits
 |                     # or

 (?:                   # either...
  \d*                  # only digits (optional)
  |                    # or
  \d{1,3}(?:,\d{3})+   # comma-separated digits
 )                     # followed by...
 \.\d+                 # a dot and digits.

)                      # end of alternation
$                      # end of string.
Tim Pietzcker
It doesn't catch /^[+-]?(?:\d+|\d*\.\d+|\d{1,2}(?:,\d{3})+\.?\d*)$/.test('100,000,000,000')
Alin Purcaru
It matches `100,00,0000` or `0,0,0,0` or `00`
Alin Purcaru
No, it doesn't. What makes you think it does?
Tim Pietzcker
I probably tested with the old one. My bad. The only problem I can find is that it also matches `100,000000`.
Alin Purcaru
No, it doesn't. Are you copying it wrong?
Tim Pietzcker
+1  A: 

For the English style DD,DDD.DD:

^[+-]?(([1-9]\d{0,2})(([,]\d{3})*|\d*)([.]\d+)?|0?([.]\d+)|0)$

For both DD,DDD.DD and DD.DDD,DD

^[+-]?(([1-9]\d{0,2})(([,]\d{3})*|\d*)([.]\d+)?|0?([.]\d+)|([1-9]\d{0,2})(([.]\d{3})*|\d*)([,]\d+)?|0?([,]\d+)|0)$

Here is how it works

Hope I didn't miss anything. Please say if you find examples that don't work.

Alin Purcaru
It matches `100,000,000000` as well as `1,1`, `1,11`...
Tim Pietzcker
1,1 and 1,11 are valid in other locales. Mine for example
Alin Purcaru
`100,000,000000` no longer validates in the long version.
Alin Purcaru