使用 python 与 coursera 上的操作系统交互的课程中关于正则表达式的问题

Question on regex from course using python to interact with operating system on coursera

Fill in the code to check if the text passed includes a possible U.S. zip code, formatted as follows: exactly 5 digits, and sometimes, but not always, followed by a dash with 4 more digits. The zip code needs to be preceded by at least one space, and cannot be at the start of the text.

import re

def check_zip_code (text):
    result = re.search(r"___", 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

用答案替换破折号 ____。这是我的 "[0-9][0-9][0-9][0-9][0-9].*[0-9][0-9][0-9][0-9]" 这个解决方案是绝对正确的,并且工作正常。任何人都可以找到解决此问题的替代解决方案,因为我不这么认为。写了这么多次[0-9]可能会有更好的解决方案。

def check_zip_code(text):
    return re.search(r'\d{5}(?:-\d{4})?', text) != None

我正好使用 5 位数字 ({n}),后跟一个 non-capturing 组 ((?: ..)),由于问号,这是可选的。