Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Get US Zip Code

Tags:

python

regex

How do I "extract" zip code (US) from the following string?

import re
address = "Moab, UT 84532"
postal_code = re.match('^\d{5}(-\d{4})?$', address)
print postal_code
like image 431
howtodothis Avatar asked Dec 02 '22 01:12

howtodothis


1 Answers

Firstly, you are using match, which will match only from the beginning of the string: see http://docs.python.org/library/re.html#matching-vs-searching

Also, even if you were using search, you are not grabbing the group that includes the 5 digits that are guaranteed to be there.

Lastly, even if you were using search, starting your regex with a carat ^ will force it to search from the beginning, which obviously won't work in your case.

>>> postal_code = re.search(r'.*(\d{5}(\-\d{4})?)$', address)
>>> postal_code.groups()
('84532', None)
like image 189
sberry Avatar answered Dec 12 '22 15:12

sberry