pb_ng
pb_ng

Reputation: 361

Regex to match ZIP in an address

I have address blocks such as

10004 South 152nd St. #A
Omaha
Nebraska
68138  United States

I am trying to find a RegEX that would match the ZIP code only and not pick up the number in the street.

I tried \d+ but it picks up the first set of numbers in the street. There are about a 1000 addresses like this.

Kindly advise

Thanks

Upvotes: 1

Views: 192

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

Assuming all the addresses are U.S. ones, you may match the numbers that are followed with 1+ whitespaces and the United States words.

\d+(?=\s+United States)

See the regex demo

The (?=\s+United States) positive lookahead will require the whitespaces and United States after 1+ digits (\d+) but won't return that text in the match value. Alternatively, you may use capturing group:

(\d+)\s+United States

And grab Group 1 value.

It might be a good idea to also make your regex case insensitive with the (?i) / /i modifier.

Upvotes: 2

Related Questions