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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13555905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:40:47  来源:igfitidea点击:

How to match exactly 3 digits in PHP's preg_match?

phpregexstringpreg-match

提问by David

Lets say you have the following values:

假设您有以下值:

123
1234
4567
12
1

I'm trying to right a preg_match which will only return true for '123' thus only matching if 3 digits. This is what I have, but it is also matching 1234 and 4567. I may have something after it too.

我正在尝试纠正一个 preg_match,它只会为“123”返回 true,因此只匹配 3 位数字。这是我所拥有的,但它也匹配 1234 和 4567。我也可能在它之后有一些东西。

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

回答by Martin Ender

What you need is 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.

它们表示字符串的开始和结束。您需要它们的原因是通常正则表达式匹配会尝试在主题中找到任何匹配的子字符串。

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\ndoes not result in a match), use the Dmodifier:

正如 rambo coder 指出的那样,$如果最后一个字符是一个新行,那么也可以在字符串中的最后一个字符之前匹配。要更改此行为(以便456\n不会导致匹配),请使用D修饰符:

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

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

或者,使用\zwhich 总是匹配字符串的最后,不管修饰符如何(感谢 Ω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);

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

现在它也会匹配123abcabc123def使用负向后看,同样可以应用于正则表达式的开头(如果应该给出匹配):

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

Further reading about lookaround assertions.

关于环视断言的进一步阅读。

回答by Andy Lester

You need to anchor the regex

您需要锚定正则表达式

/^\d{3}$/

回答by ?mega

If you are searching for 3-digit number anywhere in text, then use regex pattern

如果您要在文本中的任何位置搜索 3 位数字,请使用正则表达式模式

/(?<!\d)\d{3}(?!\d)/

However if you check the input to be just 3-digit number and nothing else, then go with

但是,如果您检查输入只是 3 位数字而没有其他内容,那么请使用

/\A\d{3}\z/