匹配字符串中的精确数字(不匹配较大数字中的部分数字)


match exact number in string (and no partial match inside bigger numbers)

我想在字符串中匹配一个精确的数字。例如,我搜索"123",并希望在"123", "asdf123x", "99 123"中匹配它,但如果它只是在"更大"的数字中部分匹配,则不匹配。所以它不会匹配"0123", "1234", "123123"

因为"asdf123x"我不能使用字边界。我试着从这样一个消极的向前看开始(并计划在后面添加一个消极的向前看),但即使向前看本身也不像我想象的那样工作:

$string = "123"; //or one of the other examples   
preg_match('/(?!'d)123/',$string,$matches);

你既需要向后看,也需要向前看:

'/(?<!'d)123(?!'d)/'
  ^^^^^^^   ^^^^^^

参见regex演示。

如果123之前有一个数字,则(?<!'d)后面的负向查找将匹配失败,如果123之后有一个数字,则负向查找将匹配失败。

查看更多关于负面搜索在这里。

PHP演示:

$string = "123"; //or one of the other examples   
if (preg_match("/(?<!'d)$string(?!'d)/", "123123",$matches)) {
    echo "Matched!";
} else {
    echo "Not matched!";
}