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.
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})?$/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With