Regex beginner zip-code validation pattern us-zip

How to Match US ZIP Codes with Regex?

Match US ZIP Codes is a Regex pattern that this regex pattern matches us zip codes in both 5-digit and zip+4 formats.. Formula Genius generates and validates this formula automatically from a plain-English prompt.

Understanding ZIP code formats is essential for data validation. This regex pattern helps you accurately identify both standard and extended ZIP codes.

The Formula

Prompt

"Match US ZIP codes in both 5-digit (12345) and ZIP+4 (12345-6789) formats"

Regex
^(\d{5})(?:-(\d{4}))?$

This regex pattern matches US ZIP codes in both 5-digit and ZIP+4 formats.

Step-by-Step Breakdown

  1. The pattern starts with ^ to indicate the beginning of the string.
  2. The \d{5} matches exactly five digits representing the standard ZIP code.
  3. The (?:...) is a non-capturing group that allows for optional matching.
  4. The - matches the hyphen in the ZIP+4 format.
  5. The \d{4} matches exactly four digits representing the extended ZIP code.
  6. $ indicates the end of the string.

Edge Cases & Warnings

  • Input with letters or special characters will not match.
  • ZIP codes with less than 5 digits will not match.
  • ZIP codes with more than 10 characters will not match.
  • Incorrect formats like 1234 or 12345-678 will not match.

Examples

Prompt

"12345"

Regex
Match
Prompt

"12345-6789"

Regex
Match

Frequently Asked Questions

What does this regex pattern do?

It matches US ZIP codes in both 5-digit and ZIP+4 formats.

Can this regex handle invalid ZIP codes?

No, it only matches valid formats.

How can I test this regex?

You can use online regex testers or implement it in programming languages that support regex.

Can't find what you need?

Describe any formula in plain English and Formula Genius will generate, explain, and validate it — instantly.