5

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:

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

But it doesn't work.

5
  • 3
    /^(\d{5})(\d{4})?)$/? Assuming that the digits are the only thing in the string, this would match 5 digits, optionally followed by 4 more. Commented Jan 27, 2011 at 13:48
  • @MarcB: That's not even syntactically valid. Commented Jan 27, 2011 at 13:54
  • Cuirious, what would the empty string tell you? Commented Jan 27, 2011 at 18:21
  • Better ways to do zip code validation... Commented Jan 14, 2014 at 21:36
  • possible duplicate of PHP: Simple regular expressions to match length? Commented Jun 27, 2014 at 12:18

5 Answers 5

17

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.

Sign up to request clarification or add additional context in comments.

Comments

4

use anchors and "?" to allow empty string

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

Comments

3
~^(?:\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.

Comments

1

"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)

Comments

1

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}|)$/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.