正则表达式 - 匹配两位小数和千位分隔符的数字

时间:2016-08-08 11:11:34

标签: php regex

http://www.tehplayground.com/#0qrTOzTh3

$inputs = array(
    '2', // no match
    '29.2', // no match
    '2.48',
    '8.06.16', // no match
    '-2.41',
    '-.54', // no match
    '4.492', // no match
    '4.194,32',
    '39,299.39',
    '329.382,39',
    '-188.392,49',
    '293.392,193', // no match
    '-.492.183,33', // no match
    '3.492.249,11',
    '29.439.834,13',
    '-392.492.492,43'
);

$number_pattern = '-?(?:[0-9]|[0-9]{2}|[0-9]{3}[\.,]?)?(?:[0-9]|[0-9]{2}|[0-9]{3})[\.,][0-9]{2}(?!\d)';

foreach($inputs as $input){
    preg_match_all('/'.$number_pattern.'/m', $input, $matches);
    print_r($matches);
}

1 个答案:

答案 0 :(得分:1)

看来你正在寻找

$number_pattern = '-?(?<![\d.,])\d{1,3}(?:[,.]\d{3})*[.,]\d{2}(?![\d.])';

请参阅PHP demoregex demo

不使用锚点,而是在图案的两侧都有外观。

模式详情

  • -? - 一个可选的连字符
  • (?<![\d.,]) - 当前位置不能有数字,逗号或点数 - \d{1,3} - 1到3位数字
  • (?:[,.]\d{3})* - 逗号或点的零个或多个序列,后跟3个数字
  • [.,] - 逗号或点
  • \d{2} -
  • 的2位数字
  • (?![\d.]) - 后面没有数字或点。

注意在PHP中,您不需要指定/m MULTILINE模式并使用$字符串锚点结束,

preg_match_all('/'.$number_pattern.'/', $input, $matches);

足以匹配较大文本中所需的数字。

如果您需要将它们作为独立字符串匹配,使用更简单的

^-?\d{1,3}(?:[,.]\d{3})*[.,]\d{2}$

请参阅regex demo

相关问题