How to split a 3 letter or a 2 letter city name from a string

Hello everyone :slight_smile:

I have a string variable,
ZipCode = “Salt Lake City CA 78978” or “New York NY 76521-1234”

My requirement is to split the above strings into 3 sets basically
So the output should be following format,
Salt Lake City (City Name) or New York (City Name)
CA (State Name) or NY (State Name)
78978 (Zip Code) or 76521-1234 (Zip Code)

If its a single word city name, the following is working well for me
ZipCode.Split({" “,”-“,”,"},StringSplitOptions.None)(0)

but need help with other 2 kinds of scenario !
Any help will be much appreciated.

Thanks in advance :slight_smile:
Happy Automation

HI @bibinthomas

Checkout this expression

City Name

System.Text.RegularExpressions.Regex.Match(ZipCode,".*(?=\s[A-Z]+\s\d)").ToString.Trim

image

State Name

System.Text.RegularExpressions.Regex.Match(ZipCode,"\S+(?=\s\d)").ToString.Trim

image

ZipCode

System.Text.RegularExpressions.Regex.Match(ZipCode,"(?<=[A-Z]\s).*").ToString.Trim

image

Hope this Helps!

Regards
Sudharsan

1 Like

Hi bibinthomas,

Try below expressions.

To get a city name.

system.text.RegularExpressions.Regex.Match(“New York NY 76521-1234”,“(.*(?=[A-Z]{2}))”).Value.Trim

To get a state name

system.text.RegularExpressions.Regex.Match("Salt Lake City CA 78978","([A-Z]{2})").Value.Trim

To get a Zip Code

system.text.RegularExpressions.Regex.Match("Salt Lake City CA 78978","((?<=[A-Z]{2}).*)").Value.Trim

Thanks!

Thanks @Sudharsan_Ka
For your very quick response…
I just have one more doubt here, the above regex works well if the delimiter is space(" ")

But what if the string is something like “Salt Lake City-CA-78789-7878”
or for that matter, “Salt Lake City,CA,78789-7878”

Your response sort of helps my half concern, but when the delimiters changes then it might not work as expected.

Checkout this @bibinthomas

City Name

System.Text.RegularExpressions.Regex.Replace(System.Text.RegularExpressions.Regex.Match(ZipCode,"^\S.+(?<=\b.[A-Z])").ToString.Trim,".[A-Z]+$]","").Trim

image

State Name

System.Text.RegularExpressions.Regex.Match(ZipCode,"[A-Z]+(?=.\b\d)").ToString.Trim

image

Zip Code

System.Text.RegularExpressions.Regex.Match(ZipCode,"\d.*$").ToString.Trim

image

1 Like

Thank you so much once again @Sudharsan_Ka :slight_smile:

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.