I recently heard that regular expressions aren't a good way to validate email addresses, postal codes, and similar structured input. Why is that? Are the main concerns performance, security, compatibility with valid formats, or something else?
5 Answers
There’s also a theory issue: email syntax is described by a much more complicated grammar than the regular languages that regex is designed for. A simple expression can handle common cases, but a pattern that attempts to cover every standard-compliant address becomes extremely difficult to read, maintain, and test. Parsing components separately, or using a well-tested library, is usually safer.
Postal codes are a separate problem because their formats vary by country and can change over time. A regex can check whether a code has the expected shape, but it cannot tell you whether that code actually exists or corresponds to the intended location. For important deliveries, use country-specific rules and, when possible, a maintained address or postal database lookup.
Security can matter when the regex is processed by a backtracking engine. Poorly designed patterns with nested or overlapping quantifiers can cause catastrophic backtracking, allowing an attacker to consume excessive CPU with a specially crafted input. This is commonly called regular-expression denial of service, or ReDoS. Length limits and safe, well-tested patterns reduce the risk.
For normal email fields, a reasonable sanity check—such as limiting length, rejecting whitespace, and checking for a basic structure—is usually enough. Then send a confirmation message when ownership matters. Be careful not to treat a regex match as proof that the mailbox exists, and make the verification endpoint rate-limited so it cannot be abused.
Email addresses allow far more formats than most people expect, including plus tags, apostrophes, unusually long domains, and other less common but valid forms. A strict regex often rejects legitimate users, while a loose one may accept something that looks right but does not actually exist. The only practical way to confirm an address belongs to someone is to send a verification link.
So the problem is mostly that strict patterns add complexity while still not proving the address is real. That makes sense.

That approach works well for signups, but it may not be practical when processing a large list of addresses. In those cases, lightweight syntax checks are still useful, but they should not be overly restrictive.