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

前端 未结 2 715
日久生厌
日久生厌 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:41

    You could use

    (?!\A)\b\d{5}(?:-\d{4})?\b
    

    Full code:

    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
    


    Meanwhile I found that there's a package called zipcodes which might be of additional help.

提交回复
热议问题