正则表达式匹配逗号分隔的数字具有可选的小数部分 [英] RegEx to match comma separated numbers with optional decimal part

查看:949
本文介绍了正则表达式匹配逗号分隔的数字具有可选的小数部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正则表达式匹配逗号分隔的数字,在一个给定的多行文本可选两位小数部分。

I've a regex that matches comma separated numbers with an optional two digit decimal part in a given multiline text.

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

它匹配像1,12,12.34,成功12,345.67等字符串。如何修改它的一些搭配只喜欢 0.23

编辑:只是为了澄清 - 我想修改的正则表达式,使其符合 12 12.34 0.34

Just to clarify - I would like to modify the regex so that it matches 12, 12.34 and .34

和我期待的'独立'的有效数字。即,数字串,其边界要么是空白或启动/行/字符串的结尾。

And I am looking for 'stand alone' valid numbers. i.e., number-strings whose boundaries are either white space or start/end of line/string.

推荐答案

本:

\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

如果你想为排除 123A 号码(街道地址为例),或 123.123 (数字超过2小数点后的数字),请尝试:

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|$)

一个小的演示(我猜你正在使用PHP):

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);
}

这将输出:

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

)

请注意,它忽略了字符串 666A 666.666

Note that it ignores the strings 666a and 666.666

这篇关于正则表达式匹配逗号分隔的数字具有可选的小数部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆