c# - Regex to group Zip Code , City and State -
i have following string
"98225-2077 bellingham wa"
i need use regex separate zip code, city , state. groups should return (98225-2077)(bellingham) , (wa). state optional , @ end , consist of 2 uppercase charachters.
i able filter out following using regex
zip code : (^([\s]+-)?\d+(-\d+)?)
- group[1]
city: ((^([\s]+-)?\d+(-\d+)?)\s)?(\s.*)
= group[5].
can there single regex filter out 3 using same regex , return blank in case state not there?
i opt splitting string on space , using various parts need. because city name may consist of multiple words, iterate second next-to-last element build city name. solution assumes zip code , state 2 abbreviation single words.
string address = "98225-2077 bellingham wa"; string[] tokens = address.split(' '); string city = ""; (int i=1; < 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]);
Comments
Post a Comment