Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for state abbreviations (python)

Tags:

python

regex

I am trying to create a regex that matches a US state abbreviations in a string using python.

The abbreviation can be in the format:

CA
Ca

The string could be:

Boulder, CO 80303
Boulder, Co
Boulder CO
...

Here is what I have, which obviously doesn't work that well. I'm not very good with regular expressions and google didn't turn up much.

pat = re.compile("[A-Za-z]{2}")
st = pat.search(str)
stateAbb = st.group(0)
like image 241
Joe Avatar asked Feb 22 '10 18:02

Joe


2 Answers

A simple and reliable way is to have all the states listed:

states = ['IA', 'KS', 'UT', 'VA', 'NC', 'NE', 'SD', 'AL', 'ID', 'FM', 'DE', 'AK', 'CT', 'PR', 'NM', 'MS', 'PW', 'CO', 'NJ', 'FL', 'MN', 'VI', 'NV', 'AZ', 'WI', 'ND', 'PA', 'OK', 'KY', 'RI', 'NH', 'MO', 'ME', 'VT', 'GA', 'GU', 'AS', 'NY', 'CA', 'HI', 'IL', 'TN', 'MA', 'OH', 'MD', 'MI', 'WY', 'WA', 'OR', 'MH', 'SC', 'IN', 'LA', 'MP', 'DC', 'MT', 'AR', 'WV', 'TX']
regex = re.compile(r'\b(' + '|'.join(states) + r')\b', re.IGNORECASE)

Use another state list if you want non-US states.

like image 146
Max Shawabkeh Avatar answered Oct 19 '22 23:10

Max Shawabkeh


re.search(r'\b[a-z]{2}\b', subject, re.I)

it will find double-letter names of towns, though

like image 43
SilentGhost Avatar answered Oct 19 '22 23:10

SilentGhost