Vinayak Phal
Vinayak Phal

Reputation: 8919

Regular Expression checking for numeric length

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

Answers (3)

Hemant Metalia
Hemant Metalia

Reputation: 30648

The following regex should work.

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

Upvotes: 6

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Matching USPS ZIP+4

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'

Corpus

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

Bohemian
Bohemian

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

Related Questions