RegEx to match comma separated numbers with optional decimal part

拜拜、爱过 提交于 2019-11-27 05:21:39

This:

\d{1,3}(,\d{3})*(\.\d\d)?|\.\d\d

matches all of the following numbers:

1
12
.99
12.34 
12,345.67
999,999,999,999,999.99

If you want to exclude numbers like 123a (street addresses for example), or 123.123 (numbers with more than 2 digits after the decimal point), try:

(?<=\s|^)(\d{1,3}(,\d{3})*(\.\d\d)?|\.\d\d)(?=\s|$)

A little demo (I guessed you're using PHP):

$text = "666a 1 fd 12 dfsa .99 fds 12.34 dfs 12,345.67 er 666.666 er 999,999,999,999,999.99";
$number_regex = "/(?<=\s|^)(?:\d{1,3}(?:,\d{3})*(?:\.\d\d)?|\.\d\d)(?=\s|$)/";
if(preg_match_all($number_regex, $text, $matches)) {
  print_r($matches);
}

which will output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 12
            [2] => .99
            [3] => 12.34
            [4] => 12,345.67
            [5] => 999,999,999,999,999.99
        )

)

Note that it ignores the strings 666a and 666.666

/(?<=\s|^)(\d{1,3}(,\d{3})*(\.\d{2})?|\.(\d{2}))(?=\s|$)/m

Or taking into account some countries where . is used as a thousand seperator, and , is used as a decimal seperator

/(?<=\s|^)(\d{1,3}(,\d{3})*(\.\d{2})?|\d{1,3}(\.\d{3})*(,\d{2})?|\.(\d{2})|,(\d{2}))(?=\s|$)/m

Insane Regex for Internationalisation

/((?<=\s)|(?<=^))(((\d{1,3})((,\d{3})|(\.\d{3}))*(((?<=(,\d{3}))(\.\d{2}))|((?<=(\.\d{3}))(,\d{2}))|((?<!((,\d{3})|(\.\d{3})))([\.,]\d{2}))))|([\.,]\d{2}))(?=\s|$)/m

Matches

14.23
14,23
114,114,114.23
114.114.114,23

Doesn't match

14.
114,114,114,23
114.114.144.23
,
.
<empty line>
tchrist

This answer treats with this question more comprehensively.

(@"^((([0-9]+)(.([0-9]+))?)(\,(([0-9]+)(.([0-9]+))?))*)$")

This works for comma separated whole number or comma separated decimal numbers.

Example: Happy scenarios: case 1) 9,10 case 2) 10.1,11,12,15,15.2 case 3) 9.8 case 4) 9

Sad scenarios: case 1) 2..7 case 2) 2,,7 case 3) 2. case 4) 7, case 5) , case 6) . case 7) .2 case 8) ,2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!