开发者

Regular expression for commonly understandable number formats

What is a regex开发者_C百科 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


^[+-]?(?:\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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜