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. Other situations is invalid. I am using the next regex开发者_C百科:
/\d{5}|\d{9}/
But it doesn't work.
Just as Marc B said in the comments, I would use this regular expression:
/^(\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)
The answer as to why it doesent work is with Perl style regex's alternations are prioritized from left to right.
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{5}|\d{9}|)$/
精彩评论