[Tutor] matching a street address with regular expressions

Ricardo Aráoz ricaraoz at gmail.com
Thu Oct 4 14:31:00 CEST 2007


Christopher Spears wrote:
> One of the exercises in Core Python Programming is to
> create a regular expression that will match a street
> address.  Here is one of my attempts.
> 
>>>> street =  "1180 Bordeaux Drive"
>>>> patt = "\d+ \w+"
>>>> import re
>>>> m = re.match(patt, street)
>>>> if m is not None: m.group()
> ...
> '1180 Bordeaux'
> 
> Obviously, I can just create a pattern "\d+ \w+ \w+". 
> However, the pattern would be useless if I had a
> street name like 3120 De la Cruz Boulevard.  Any
> hints?
> 

Maybe :

r'^(\d+)\s+(.*?)(?:\s+)?(\d+.*)?$'

street = "1180 Bordeaux Drive 5th floor apt 'A'"
then :
\1 : '1180'
\2 : 'Bordeaux Drive'
\3 : "5th floor apt 'A'"

or :
street = "1180 Bordeaux Drive"
then :
\1 : '1180'
\2 : 'Bordeaux Drive'
\3 : ""




More information about the Tutor mailing list