正则表达式过滤正数和负数

时间:2012-02-15 12:50:48

标签: php regex

我使用以下函数来过滤字符串中的数字(包括一些特殊情况,例如价格(以$开头)):

function _process_numbers($string) {
return preg_replace(
   '/(?<!\{)         # Assert no preceding {
    (?<![^\s$-])     # Assert no preceding non-whitespace except $-
    \b               # Match start of number
    (\d+(?:\.\d+)?+) # Match number (optional decimal part)
    \b               # Match end of number
    (?![^{}]*\})     # Assert that next brace is not a closing brace
    (?![^\s.!?,%])   # Assert no following non-whitespace except .!?,%
    /x', 
    '{NUMBER|\1}', $string
  );
}

echo _process_numbers("100.000.000 and -0.33 and $100.50 and 0.06%");

这很有效,除了(1)减去“ - ”应该包含在输出的括号内,(2)应该支持最多10亿(和减去10亿)的数字。换一种说法;以上作为输出返回:

{NUMBER|100.000}.000 and -{NUMBER|0.33} and ${NUMBER|100.50} and {NUMBER|0.06}%

但预期的输出是:

{NUMBER|100.000} and {NUMBER|-0.33} and ${NUMBER|100.50} and {NUMBER|0.06}%

应该改变什么?

1 个答案:

答案 0 :(得分:2)

应该做的诀窍:

(-?\d+(?:\.\d+)?+) # Match number (optional decimal part)

<强>更新

从后面的断言中删除 - 捕获第一个(\b-)。

<?php

function _process_numbers($string) {
return preg_replace(
   '/(?<!\{)         # Assert no preceding {
    (?<![^\s$])     # Assert no preceding non-whitespace except $-
    (\b|-)               # Match start of number
    (\d+(?:\.\d+)*) # Match number (optional decimal part)
    \b               # Match end of number
    (?![^{}]*\})     # Assert that next brace is not a closing brace
    (?![^\s.!?,%])   # Assert no following non-whitespace except .!?,%
    /x', 
    '{NUMBER|\1\2}', $string
  );
}

echo _process_numbers("100.000.000 and -0.33 and $100.50 and 0.06%"), "\n";