regexp-用两个小数和千分隔符匹配数字


regexp - match numbers with two decimals and thousand seperator

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

您似乎在寻找

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

请参阅PHP演示和regex演示。

锚没有使用,而是在图案的两侧都有环视。

图案详细信息

  • -?-可选连字符
  • (?<!['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演示。