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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With