Take the 2-minute tour ×

I need to extract name, street1, street2, city, state, zip

I have data in this form


My results for JOHN should be

name="JOHN m SMITH"
street1="1111 WEST OAK ROAD"
street2="SUITE 101"
city = "CITY"
state = "ST"
zip = "55555"

This works with GEORGE's data

            Regex r = new Regex(@"^(?<name>.*)\[(?<street>.*)[,]\s(?<city>.*)[,]\s(?<state>.*)\s(?<zip>\d{5})\]$");
            var match = r.Match(fullNameAndAddress);
            name = match.Groups["name"].Value;
            street = match.Groups["street"].Value;
            city = match.Groups["city"].Value;
            state = match.Groups["state"].Value;
            zip = match.Groups["zip"].Value;

How do I add the optional street2?

I want 1 and only 1 "street" group. I thought it should have this: (....){1}?

street2 is optional zero or 1 times. I thought it should have this (...)?

but it doesn't work with JOHN's data, both street1 & street2 are going into the street group:

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

Could you clarify what you want stored in street?

Do you want John's to look like '1111 WEST OAK ROAD, SUITE 101'?

Or do you want to stuff it into some variable you wont be using, so that street looks like '1111 WEST OAK ROAD'?

Edit: With clarification, check out this link


What happens here I believe is that the * is greedy, grabbing as much as it can before finding the final occurence of [,]\s

Adding a ? after the .* makes it lazy, grabbing the least information possible.

The amended regex looks like this


You'll notice I changed the Regex for state from .* to .{2}, forcing a 2-character state. Feel free to revert that if you don't want it :)

share|improve this answer
Clarified question (I hope) I want "SUITE 101" in a variable I can access. –  Brad Boyce Sep 20 '12 at 2:46
{2} character state is good. Thanks for explaining lazy loading. –  Brad Boyce Sep 20 '12 at 3:01
add comment

I made a couple of changes to your regex in rubular.com, and it seemed to be working on both the example strings:


street2 = match.Groups["street2"].Value;

One trick I've learned with regex's is to use the negation of the divider (eg. [^,]* for anything but a comma) instead of .*, so it's impossible to capture multiple fields with one expression. Also, the + operator, which requires at least one match, is useful in most of the groups.

Also, the additional comma is only there if there's an street2 component of the address, which indicates that the comma should be in the same capture group as the street2 part. I added an extra capture group around the street2 capture group to account for this. You can make groups non-capturing in most languages, but it didn't seem necessary.

share|improve this answer
add comment

Your Answer


