Rahul Chandran
Rahul Chandran

Reputation: 5

How do I use RegEx to extract something ending in zipcode

If I have some text in the format Mail To - {what i want to extract) 98012-2345 what do I do? I dont seem to be able to get the regex to get that the termination will be

ddddd-dddd

So far I have tried a pattern of MAIL TO (.*) [ddddd]-[dddd]

This is using .Net 4.6.

Upvotes: 0

Views: 65

Answers (1)

Sebastian Lenartowicz
Sebastian Lenartowicz

Reputation: 4864

The ZIP code regex you want looks like this:

\d{5}(?:-\d{4})?

What you have up there can be collapsed down to simply [d]-[d], and even further to d-d, meaning it will match two literal d characters separated by a hyphen, which is clearly not what you're after.

In the regex I provided, I've made the second part of the ZIP code optional (as it is in many cases), meaning you'll match both partial (5-digit) and complete (9-digit) ZIP codes. Just be sure to actually validate the ZIP code, as that isn't something I'd recommend doing with a regex.

Upvotes: 1

Related Questions