Regular Expression for Street Address Validation in Java: What It Can and Cannot Check

A practical review of using Java regular expressions to validate US street address lines: what a pattern checks, how normalization changes stored text, Unicode and copy/paste pitfalls, and when to use a verification service instead.

Developers often reach for a regular expression to validate the street line of a US address in a Java form or import job. A regex can reject obvious junk and enforce a consistent shape. It cannot tell you whether an address exists or can receive mail. This review covers when a regex check is worth using, what it changes in the input, and where it breaks down. It includes a pattern you can adapt.

Is regex validation suitable for your use?

Recommendation: use a permissive regex as a plausibility filter on a single street line, and do not use it as the final decision on whether an address is valid. The main benefit is cheap, local, instant feedback. It catches empty fields, stray symbols, pasted markup and a missing house number before the data reaches storage or a paid lookup. The decisive tradeoff is that US addressing has many legitimate formats. A pattern strict enough to feel rigorous will reject real addresses, and a pattern loose enough to accept them will also accept many nonexistent ones.

Accept the text as entered, with only light cleanup, in these situations: the address is shown back to a person but not mailed; the input is international; or a wrongly rejected address costs more than an imperfect one. If you need to know that mail will arrive, you need an address verification service checked against postal data. In the US, look for CASS-certified providers. Treat any regex as the first step in that process, not a replacement for it.

What the pattern actually checks and what it changes

Matching a regex does not change the input string. java.util.regex.Pattern compiles the expression, and Matcher reports whether the text fits. Matcher.matches() requires the whole input to match. Matcher.find() succeeds if any substring matches. Using find() by mistake is a common reason a validator accepts input it should reject.

The stored characters change only in the normalization step. That step usually runs before matching: trimming, collapsing whitespace, applying Unicode normalization and sometimes converting to uppercase. Each of these rewrites the text, so decide whether to store the normalized form, the original, or both. A common approach is to keep the original for display and audit, and to use the normalized form for matching and deduplication.

The example below targets one US street line: a house number, street words and an optional unit designator. It uses a Java text block, which requires Java 15 or later, together with the COMMENTS flag, which ignores whitespace and lets you annotate each part. Backslashes still need doubling inside a text block. Under COMMENTS, a literal space has to be written as an escape (here \x20), and a literal # has to be escaped because # starts a comment.

import java.text.Normalizer;
import java.util.regex.Pattern;

public final class StreetLineValidator {

    // Compiled once; Pattern is immutable and safe to share across threads.
    private static final Pattern STREET_LINE = Pattern.compile("""
            ^
            (?<number> \\d{1,6} [A-Z]? (?: - \\d{1,6} [A-Z]? )? (?: \\x20 \\d/\\d )? )  # house number
            \\x20
            (?<street> [\\p{L}\\p{M}\\d.'\\-]+ (?: \\x20 [\\p{L}\\p{M}\\d.'\\-]+ ){0,8}? )  # street words
            (?: \\x20 (?<unit> (?:APT|UNIT|STE|SUITE|\\#) \\x20? [A-Z0-9\\-]{1,8} ) )?    # optional unit
            $
            """,
            Pattern.COMMENTS | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);

    private StreetLineValidator() {
    }

    public static String normalize(String raw) {
        String s = Normalizer.normalize(raw, Normalizer.Form.NFKC);
        s = s.replaceAll("\\p{Cf}", "");
        s = s.replaceAll("[\\p{Z}\\s]+", " ");
        return s.strip();
    }

    public static boolean isPlausibleStreetLine(String raw) {
        return raw != null && STREET_LINE.matcher(normalize(raw)).matches();
    }
}

Here is what each part does. The number group accepts one to six digits, an optional letter suffix, an optional hyphenated second part and an optional fraction such as one-half. The street group accepts up to nine space-separated words made of letters, combining marks, digits, periods, apostrophes and hyphens. The unit group is optional and recognizes a short list of designators. Named groups let you pull out each part with Matcher.group("number") and similar calls, but this is only a rough split, not standardized parsing.

The pattern is built to limit backtracking. Repetitions are bounded, and every repeated street word must be separated by a mandatory space that the word class cannot match. Avoid nested open-ended quantifiers whose inner and outer parts can match the same characters, such as a group of optional words with optional separators. On long hostile input, those can cause catastrophic backtracking. Java also supports possessive quantifiers and atomic groups if you need tighter control.

This pattern has not been tested against a representative address dataset here, and no accept or reject rates are claimed. Before relying on it, build test fixtures from the categories your own data contains. Include the rejected cases you want, not only the accepted ones.

Address formats a single pattern handles poorly

Input category | Regex suitability | Practical handling
House number, street name, optional suffix and directional | Plausibility check is feasible | Main pattern; allow suffix and directional words rather than requiring them
Unit designators (apartment, suite, unit, number sign) | Feasible as an optional group | Many designators exist beyond the short list above; consider a separate second address line
Hyphenated, lettered or fractional house numbers | Feasible if explicitly allowed | Strict digits-only patterns reject these legitimate forms
PO Box lines | Needs its own pattern | Validate as a separate branch instead of widening the street pattern
Rural route and highway contract route lines | Needs its own pattern or a service | Formats differ from city-style street lines
Military and diplomatic addresses | Poor fit for a street pattern | These use different city and state values; treat as a separate address type
Streets without a suffix or with numeric names | Feasible if the suffix is optional | Requiring a suffix rejects real addresses
Whether the address exists or is deliverable | Not possible with regex | Requires an address verification service

The USPS publishes standard street suffix and unit designator abbreviations in Publication 28. If you want to standardize abbreviations, use that list as reference data in a lookup table rather than hard-coding a long alternation inside the regex.

Will input survive copy, paste and Unicode?

Pasted addresses often contain characters that look normal but defeat a naive pattern. Common examples are non-breaking spaces, zero-width characters, fullwidth digits, en dashes in place of hyphens, and curly apostrophes. Two Java defaults matter here. Without the UNICODE_CHARACTER_CLASS flag, \d matches only ASCII 0 to 9, and \s does not match the non-breaking space. The normalize method above handles several of these cases. NFKC normalization maps fullwidth digits to ASCII and the non-breaking space to a regular space. Removing format characters (\p{Cf}) strips zero-width characters. Collapsing \p{Z} and \s turns any run of separators into one space.

These steps change the stored characters, and NFKC can alter some text in ways beyond the cases listed. If you store normalized text, record that you did. Removing format characters is reasonable for US street lines, but it would damage text in scripts that depend on zero-width joiners. Curly apostrophes and en dashes are not converted by NFKC. Either add them to the character classes or map them to ASCII explicitly.

For accepted input, use \p{L} and \p{M} rather than A-Z for street names, so accented letters are accepted whether they arrive precomposed or as a base letter plus a combining mark. Reading order is not a concern for US street lines, since they are left-to-right text. Searching and deduplication work better on the normalized form.

Usability and accessibility of the validation step

Most of the usability risk comes from how a rejection is handled, not from the regex itself. Give a specific, plain-text error message that is tied to the field and says what is expected, such as a missing house number. Avoid a generic invalid-format message. Do not block submission on the regex alone. Offer a way to keep the address as entered, because a legitimate address the pattern misses is otherwise impossible to submit.

How a particular screen reader or browser announces inline errors has not been tested here. Follow your form framework's documented accessibility guidance, and test with the assistive technologies your users rely on. Do not assume that one successful check carries over to other environments.

Gaps in this review

  • No measured accept or reject rates for the sample pattern are available.
  • No comparison of specific address verification providers or Java parsing libraries was supplied.
  • No destination-specific test results for copy, paste or assistive technology behavior were supplied.
  • International address formats are outside the scope of this pattern and need different handling.