首页 > 解决方案 > 一位数的正则表达式捕获两位数?

问题描述

此正则表达式捕获两位数的数字:

如果我有 y11 它仍然会捕获它,如何仅匹配 y0、y1、y2、y3、y4、y5、y6、y7、y8、y9 ?在数字之后可能有一个空格或一个字母或一个点。

preg_replace('/y([1-9]{1})/', 'y0$1', $string)

标签: phpregex

解决方案


我会匹配 pattern y\d(?!\d),匹配y后跟一个数字,它本身后面没有另一个数字。

$string = "y2";
echo $string . "\n";
$string = preg_replace("/y(\d)(?!\d)/", "y0$1", $string);
echo $string;

这打印:

y2
y02

正则表达式的解释:

y       the letter 'y'
(\d)    a single digit (capture it)
(?!\d)  assert that what follows is either a non digit character OR
        the end of the input

推荐阅读