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

s5a0g9ez  于 2022-11-18  发布在  其他
关注(0)|答案(8)|浏览(118)

填写代码以检查传递的文本是否包含可能的美国邮政编码,格式如下:正好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
d5vmydt9

d5vmydt91#

你可以用

(?!\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的软件包可能会有额外的帮助。

xienkqul

xienkqul2#

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
voj3qocg

voj3qocg3#

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

"试试这个"

qrjkbowd

qrjkbowd4#

第一个字符必须包含空格。这只是此问题的一个示例

r"[\s][\d]{5}"
jmo0nnb3

jmo0nnb35#

试试这个代码你会得到

import re
def check_zip_code (text):
  result = re.search(r"\s+\d{5}-?(\d{4})?", text)
  return result != None
eivnm1vs

eivnm1vs6#

import re
def check_zip_code (text):
    result = re.search(r" \d{5}|\d[5]-\d{4}", text)
    return result != None
rryofs0p

rryofs0p7#

我认为这涵盖了所有情况result = re.search(r"\s\d{5}?(-\d{4})?", text)

zpgglvta

zpgglvta8#

这段代码运行良好,并生成所需的输出。
第一个

相关问题