Regex groups the postal code, city and state

advertisements

I have the following string

"98225-2077 Bellingham WA"

I need to use Regex to separate Zip Code, City and State. the groups should return (98225-2077)(Bellingham) and (WA). The State is optional and will always be at the end and will consist of two Uppercase charachters.

I am able to filter out the following using regex

Zip Code : (^([\S]+-)?\d+(-\d+)?) - Group[1]
City: ((^([\S]+-)?\d+(-\d+)?)\s)?(\S.*) = Group[5].

Can there be a single regex to filter out all the three using the same regex and return blank in case the state is not there?


I would opt for just splitting the string on space and then using the various parts as you need. Because your city name may consist of multiple words, I iterate from the second to next-to-last element to build the city name. This solution assumes that the zip code and state two abbreviation will always be single words.

string address = "98225-2077 Bellingham WA";
string[] tokens = address.Split(' ');

string city = "";
for (int i=1; i < tokens.Length-1; i++)
{
    if (i > 1)
    {
        city += " ";
    }
    city += tokens[i];
}

Console.WriteLine("zip code: {0}", tokens[0]);
Console.WriteLine("city: {0}", city);
Console.WriteLine("state: {0}", tokens[tokens.Length-1]);