美元符号与\ b在正则表达式包括额外的空间

时间:2016-12-16 01:02:35

标签: php regex regex-negation

我正在努力想出一个正则表达式来匹配价格不高的数字 100 - 应该匹配
100美元 - 不应该匹配

我尝试了[^\$]100,但它获得了100

之前的额外空间

Regex result example

我正在尝试用其他字符串替换数字。

" 100"将成为"!"

这很好,除了我想忽略以$开头的那些 " $ 100#34;成为" $!" 我不想要那个,我想要100美元被忽略。

任何想法?

2 个答案:

答案 0 :(得分:4)

只需尝试查找未加$前缀的数字,然后将其替换为前缀字符,后跟您想要的任何内容,!

$test_string = "This is a number 100 but this isn't \$100.";
$result = preg_replace('/([^\$\d])(\d+)/', '\1!', $test_string);
var_dump($result);

答案 1 :(得分:4)

使用带有单词边界的负后观:

\s*(?<!\$)\b\d+

替换为!。请参阅regex demo

<强>详情:

  • \s* - 0+ whitespaces
  • (?<!\$) - 匹配不在$
  • 之前的位置
  • \b - 领先的单词边界
  • \d+ - 1+位数(要匹配浮点数,请使用\d*\.?\d+)。

PHP demo

$str = 'This is a number 100 but this isn\'t $100.';
$re = '~\s*(?<!\$)\b\d+~';
$subst = '!';
$result = preg_replace($re, $subst, $str);
echo $result; 
// => This is a number! but this isn't $100.
相关问题