Python 如何使用正则表达式在字符串中查找美国邮政编码?
填写代码,检查传递的文本是否包含可能的美国邮政编码,格式如下:精确为5位数字,有时(但不总是)后跟一个多4位的破折号。邮政编码前面必须至少有一个空格,并且不能位于文本的开头 无法生成所需的输出Python 如何使用正则表达式在字符串中查找美国邮政编码?,python,regex,Python,Regex,填写代码,检查传递的文本是否包含可能的美国邮政编码,格式如下:精确为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 N
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
同时,我发现有一个名为的包,它可能有额外的帮助。试试你将得到的代码
import re
def check_zip_code (text):
return bool(re.search(r" (\b\d{5}(?!-)\b)| (\b\d{5}-\d{4}\b)", text))
assert check_zip_code("The zip codes for New York are 10001 thru 11104.") is True
assert check_zip_code("90210 is a TV show") is False
assert check_zip_code("Their address is: 123 Main Street, Anytown, AZ 85258-0001.") is True
assert check_zip_code("The Parliament of Canada is at 111 Wellington St, Ottawa, ON K1A0A9.") is False
assert check_zip_code("x\n90201") is False
assert check_zip_code("the zip somewhere is 98230-0000") is True
assert check_zip_code("the zip somewhere else is not 98230-00000000") is False
import re
def check_zip_code (text):
result = re.search(r"\s+\d{5}-?(\d{4})?", text)
return result != None
试试这个考虑到邮政编码前面必须有空格,要求“…不能在文本开头”是多余的。您可以通过让正则表达式断言(替换)所需的五个数字构成一个空格来区分您的答案。我已经记了一张便条,下周再来看看你有没有这样做。你肯定不认为我的建议是认真的@卡利斯沃维兰:好吧,你等一下-是的,我有。这是匹配的'12345-'或'123456789',但不是
12345
import re
def check_zip_code (text):
result = re.search(r" \d{5}|\d[5]-\d{4}", text)
return result != None
import re
def check_zip_code (text):
result = re.search(r"\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