如何使用正则表达式在字符串中查找美国邮政编码?

问题描述 投票:0回答:2

填写代码,检查所传递的文本是否包含可能的美国邮政编码,格式如下:恰好是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
python regex
2个回答
1
投票

您可以使用

(?!\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


同时,我发现有一个叫作 zipcodes 可能会有更多的帮助,

1
投票
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

© www.soinside.com 2019 - 2024. All rights reserved.