Regex 101 Exercise S3 – Validate a zip+4 zip code

Exercise S3 – Validate a zip+4 zip code.

The US has a 5 digit zip code with an optional 4 digit suffix. Write a regex to validate that the input is in the proper format:

Sample strings


I’m going to keep comments enabled in case people have questions about the exercise, but please don’t post answers in the comments.

Comments (2)

  1. It’s amazing how some people don’t read the entries all the way through. =)

    I was going to say, I’m getting good at this reg-ex thing. The answers are there if you look through the previous blog entries.

  2. Frisky says:

    An interesting one to try is a simple Email address, as defined in RFC-2822. What would seem a simple task, is quite complex. That is, for a complete definition based on the RFC.