How to find a US zip code in a string using regular expression?

前端 未结 2 694
日久生厌
日久生厌 2021-01-22 06:53

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

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-22 07:50

    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
    
    

提交回复
热议问题