Which regex matches a US ZIP code with optional 4-digit extension?

Enhance your skills with the CSS Mastery – Address Management System Test. Flashcards, multiple choice questions with hints and explanations. Boost confidence for your test!

Multiple Choice

Which regex matches a US ZIP code with optional 4-digit extension?

Explanation:
The key idea is matching a five-digit ZIP code and embracing the optional ZIP+4 extension. US ZIPs are five digits, and the ZIP+4 adds a hyphen and four more digits. To ensure the whole string fits this pattern, use start and end anchors and make the extension optional. The pattern that fits this perfectly starts with a start anchor, then five digits, then an optional group of a hyphen and four digits, and ends with an end anchor. Specifically: ^\d{5}(-\d{4})?$. Here, \d{5} enforces exactly five digits. The group (-\d{4})? makes the dash and four digits optional, so you match either five digits alone or five digits followed by - and four digits. The anchors ensure there are no extra characters before or after. Why the others don’t fit: patterns that allow letters or mix alphanumeric characters don’t restrict to digits only, so they don’t represent a standard ZIP. A pattern that requires four digits before a hyphen would describe a different format, not the five-digit base ZIP. A pattern with letters only also misses the numeric requirement entirely.

The key idea is matching a five-digit ZIP code and embracing the optional ZIP+4 extension. US ZIPs are five digits, and the ZIP+4 adds a hyphen and four more digits. To ensure the whole string fits this pattern, use start and end anchors and make the extension optional.

The pattern that fits this perfectly starts with a start anchor, then five digits, then an optional group of a hyphen and four digits, and ends with an end anchor. Specifically: ^\d{5}(-\d{4})?$. Here, \d{5} enforces exactly five digits. The group (-\d{4})? makes the dash and four digits optional, so you match either five digits alone or five digits followed by - and four digits. The anchors ensure there are no extra characters before or after.

Why the others don’t fit: patterns that allow letters or mix alphanumeric characters don’t restrict to digits only, so they don’t represent a standard ZIP. A pattern that requires four digits before a hyphen would describe a different format, not the five-digit base ZIP. A pattern with letters only also misses the numeric requirement entirely.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy