Reputation: 8919
I want to validate a zipcode either 5 digit or 9 digit.
I've written this /^(\d){5|9}$/
but its not matching anything.
But when i give /^(\d){5}$/
its matching properly for 5.
Please help.
Upvotes: 3
Views: 126
Reputation: 84343
If you're dealing with the US Postal Service's ZIP+4 format, this regular expression might provide more accurate matches:
egrep -o '\b[[:digit:]]{5}-?[[:digit:]]{4}?\b'
This regular expression was tested against a limited corpus. Your mileage may vary.
cat << EOF | egrep -o '\b[[:digit:]]{5}-?[[:digit:]]{4}?\b'
12345
123456789
12345-6789
EOF
Upvotes: 1
Reputation: 424983
Make the last four optional:
^\d{5}(\d{4})?$
Note that I removed the opening/closing slashes as they have nothing whatsoever to do with regex; they are an application language artefact.
Upvotes: 6