填写代码以检查传递的文本是否包含可能的美国邮政编码,格式如下:正好 5 位数字,有时(但并非总是)后跟带有 4 位数字的破折号。邮政编码前面至少需要一个空格,并且不能位于文本的开头。
无法产生所需的输出。
import re
def check_zip_code (text):
result = re.search(r"\w+\d{5}-?(\d{4})?", text)
return result != None
print(check_zip_code("The zip codes for New York are 10001 thru 11104.")) # True
print(check_zip_code("90210 is a TV show")) # False
print(check_zip_code("Their address is: 123 Main Street, Anytown, AZ 85258-0001.")) # True
print(check_zip_code("The Parliament of Canada is at 111 Wellington St, Ottawa, ON K1A0A9.")) # False
你可以使用
(?!\A)\b\d{5}(?:-\d{4})?\b
完整代码:
import re
def check_zip_code (text):
m = re.search(r'(?!\A)\b\d{5}(?:-\d{4})?\b', text)
return True if m else False
print(check_zip_code("The zip codes for New York are 10001 thru 11104.")) # True
print(check_zip_code("90210 is a TV show")) # False
print(check_zip_code("Their address is: 123 Main Street, Anytown, AZ 85258-0001.")) # True
print(check_zip_code("The Parliament of Canada is at 111 Wellington St, Ottawa, ON K1A0A9.")) # False
Meanwhile I found that there's a package called
zipcodes which might be of additional help.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)