overlord9314
overlord9314

Reputation: 35

Java Regex - Exclude 5 digit numbers attached by a hypen

I have a regex (?:^|[^\w])(\d{5}(?:[-\s]\d{4})?)(?:$|[^\w]).

It's looking for either a US standard 5 digit zip code or the longer 5+4 digit version.

However, this particular regex also matches on 5 digits for numbers of the following form.

1111-11111. The 11111 matches. How can I exclude this type of case?

I've tried adding the hypen to the exclusion at the beginning of the regex like so, (?:^|[^\w]|-) which had no effect.

Upvotes: 1

Views: 84

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626853

Note that you can actually use

\b(?<!-)\d{5}(?:[- ]\d{4})?(?!-)\b

which is shorter and more readable. The (?<!-) negative lookbehind will make sure no - precedes the value, (?!-) negative lookahead will make sure no - follows the value, and \b word boundaries will effectively replace the (?:^|\W) and (?:$|\W) non-capturing groups.

See the regex demo.

Upvotes: 1

Related Questions