且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在PHP的preg_match中精确匹配3位数字?

更新时间:2021-12-12 17:41:42

您需要的是 anchors :

preg_match('/^[0-9]{3}$/',$number);

它们表示字符串的开头和结尾.您之所以需要它们,是因为通常正则表达式匹配会尝试在主题中找到任何匹配的子字符串.

They signify the start and end of the string. The reason you need them is that generally regex matching tries to find any matching substring in the subject.

正如rambo编码器所指出的,如果最后一个字符是换行符,则$也可以在字符串的最后一个字符之前匹配.要更改此行为(以使456\n不会导致匹配),请使用D修饰符:

As rambo coder pointed out, the $ can also match before the last character in a string, if that last character is a new line. To changes this behavior (so that 456\n does not result in a match), use the D modifier:

preg_match('/^[0-9]{3}$/D',$number);

或者,使用\z总是匹配字符串的末尾,而不考虑修饰符(感谢Ωmega):

Alternatively, use \z which always matches the very end of the string, regardless of modifiers (thanks to Ωmega):

preg_match('/^[0-9]{3}\z/',$number);

您说过我可能还会有其他东西".如果这意味着您的字符串应以三位数字开头,但之后可以有任何内容(只要不是其他数字),则应使用负数前瞻:

You said "I may have something after it, too". If that means your string should start with exactly three digits, but there can be anything afterwards (as long as it's not another digit), you should use a negative lookahead:

preg_match('/^[0-9]{3}(?![0-9])/',$number);

现在它也将匹配123abc.可以使用负向后看法将同样的内容应用于正则表达式的开头(如果abc123def应该给出匹配项):

Now it would match 123abc, too. The same can be applied to the beginning of the regex (if abc123def should give a match) using a negative lookbehind:

preg_match('/(?<![0-9])[0-9]{3}(?![0-9])/',$number);

进一步了解环视断言.