简体   繁体   English

PHP正则表达式的数字长度只有5或9

[英]PHP regex digit length only 5 or 9

I need a regular expression for string validation. 我需要一个正则表达式进行字符串验证。 String can be empty, can have 5 digits, and can have 9 digits. 字符串可以为空,可以有5位数,也可以有9位数。 Other situations is invalid. 其他情况无效。 I am using the next regex: 我正在使用下一个正则表达式:

/\d{5}|\d{9}/

But it doesn't work. 但它不起作用。

Just as Marc B said in the comments , I would use this regular expression: 正如Marc B在评论中所说 ,我会使用这个正则表达式:

/^(\d{5}(\d{4})?)?$/

This matches either exactly five digits that might be followed by another four digits (thus nine digits in total) or no characters at all (note the ? quantifier around the digits expression that makes the group optional). 这恰好匹配五个数字,可能后跟另外四个数字(因此总共九个数字)或根本没有字符(注意数字表达式周围的?量词使组成为可选)。

The advantage of this pattern in opposite to the other mentioned patterns with alternations is that this won't require backtracking if matching five digits failed. 与其他提到的具有替换的模式相反,该模式的优点在于,如果匹配的五个数字失败,则不需要回溯。

use anchors and "?" 使用锚和“?” to allow empty string 允许空字符串

/^(\d{5}|\d{9})?$/
~^(?:\d{5}|\d{9}|)$~

You forgot the anchors ^ and $ . 你忘了锚^$ Without them the string would match those digits anywhere in the string, not only at beginning or end. 如果没有它们,字符串将匹配字符串中任何位置的数字,而不仅仅是在开头或结尾。 Furthermore you didn't cover the empty string case. 此外,你没有覆盖空的字符串案例。

"doesn't work" isn't much help. “不起作用”没有多大帮助。 but wouldn't it be something like this? 但不是这样的吗?

/^(\d{5}|\d{9}|)$/

(Bit rusty on regexp, but i'm trying to do is "start, then 5 digits OR 9 digits OR nothing, then end) (在正则表达式上有点生锈,但我想做的是“开始,然后是5位或9位数或者没有,然后结束)

The answer as to why it doesent work is with Perl style regex's alternations are prioritized from left to right. 关于它为什么会起作用的答案是Perl样式正则表达式的替换从左到右排列优先顺序。

Change it to: 将其更改为:

/\\d{9}|\\d{5}/ (Though, this won't tell you anything else about 6-8 and 10-infinity unless its anchored with assertions or something else.) /\\d{9}|\\d{5}/ (但是,除非它以断言或其他东西为基础,否则这不会告诉你任何关于6-8和10-infinity的信息。)

/^(\\d{5}|\\d{9}|)$/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM