Python, Regular Expression Postcode search

前端 未结 3 917
名媛妹妹
名媛妹妹 2021-01-03 06:54

I am trying to use regular expressions to find a UK postcode within a string.

I have got the regular expression working inside RegexBuddy, see below:



        
3条回答
  •  抹茶落季
    2021-01-03 07:46

    #!/usr/bin/env python
    
    import re
    
    ADDRESS="""123 Some Road Name
    Town, City
    County
    PA23 6NH"""
    
    reobj = re.compile(r'(\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b)')
    matchobj = reobj.search(ADDRESS)
    if matchobj:
        print matchobj.group(1)
    

    Example output:

    [user@host]$ python uk_postcode.py 
    PA23 6NH
    

提交回复
热议问题