匹配数字与可选的逗号和点

时间:2014-06-12 10:33:44

标签: java regex

使用逗号分隔千位分隔符的一个或多个数字的正则表达式是什么,后跟可选的点和小数,如下所示:

必须匹配

1 
12
123,123
123,123.000
123.123

但不是,

123.123,123

1 个答案:

答案 0 :(得分:5)

听起来像你正在寻找这样的东西(见demo):

^\d+(?:,\d{3})*(?:\.\d{3})?$
  1. 这允许多个以逗号分隔的数千个组,如12,345,678.000
  2. 请注意,句点后有三位数字(或无)。如果您想要允许一个或多个,请将\d{3}更改为\d+
  3. 解释正则表达式

    ^                        # the beginning of the string
    \d+                      # digits (0-9) (1 or more times (matching
                             # the most amount possible))
    (?:                      # group, but do not capture (0 or more times
                             # (matching the most amount possible)):
      ,                      #   ','
      \d{3}                  #   digits (0-9) (3 times)
    )*                       # end of grouping
    (?:                      # group, but do not capture (optional
                             # (matching the most amount possible)):
      \.                     #   '.'
      \d{3}                  #   digits (0-9) (3 times)
    )?                       # end of grouping
    $                        # before an optional \n, and the end of the
                             # string