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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.