正则表达式中带 \b 的美元符号包括额外的 space
Dollar Sign with \b in regex includes extra space
我正在尝试想出一个正则表达式来匹配不是价格的数字。
100 - 应该匹配
$100 - 不应该匹配
我试过了[^$]100
但是它在 100
之前得到了额外的 space
我正在尝试用其他字符串替换数字词。
“100”会变成“!”
这很好用,除了我想忽略以 $ 开头的那些
“100 美元”变成“$!”
我不想这样,我希望 100 美元被忽略。
有什么想法吗?
只需尝试查找未以 $
为前缀的数字,并用该前缀字符替换它们,然后是您想要的任何内容,在您的示例中为 !
。
$test_string = "This is a number 100 but this isn't $100.";
$result = preg_replace('/([^$\d])(\d+)/', '!', $test_string);
var_dump($result);
使用带有单词边界的负后视:
\s*(?<!$)\b\d+
替换为!
。见 regex demo.
详情:
\s*
- 0+ 个空格
(?<!$)
- 匹配不以 $
开头的位置
\b
- 前导词边界
\d+
- 1+ 位数字(要匹配浮点数,也使用 \d*\.?\d+
)。
$str = 'This is a number 100 but this isn\'t 0.';
$re = '~\s*(?<!$)\b\d+~';
$subst = '!';
$result = preg_replace($re, $subst, $str);
echo $result;
// => This is a number! but this isn't 0.
我正在尝试想出一个正则表达式来匹配不是价格的数字。
100 - 应该匹配
$100 - 不应该匹配
我试过了[^$]100
但是它在 100
我正在尝试用其他字符串替换数字词。
“100”会变成“!”
这很好用,除了我想忽略以 $ 开头的那些 “100 美元”变成“$!” 我不想这样,我希望 100 美元被忽略。
有什么想法吗?
只需尝试查找未以 $
为前缀的数字,并用该前缀字符替换它们,然后是您想要的任何内容,在您的示例中为 !
。
$test_string = "This is a number 100 but this isn't $100.";
$result = preg_replace('/([^$\d])(\d+)/', '!', $test_string);
var_dump($result);
使用带有单词边界的负后视:
\s*(?<!$)\b\d+
替换为!
。见 regex demo.
详情:
\s*
- 0+ 个空格(?<!$)
- 匹配不以$
开头的位置
\b
- 前导词边界\d+
- 1+ 位数字(要匹配浮点数,也使用\d*\.?\d+
)。
$str = 'This is a number 100 but this isn\'t 0.';
$re = '~\s*(?<!$)\b\d+~';
$subst = '!';
$result = preg_replace($re, $subst, $str);
echo $result;
// => This is a number! but this isn't 0.