[Tutor] regular expression question

Sean Perry shaleh at speakeasy.net
Wed Mar 9 03:28:21 CET 2005

Mike Hall wrote:
> First, thanks for the response. Using your re:
>> my_re = re.compile(r'(dog)(cat)?')
> ...I seem to simply be matching the pattern "Dog".  Example:
>  >>> str1 = "The dog chased the car"
>  >>> str2 = "The dog cat parade was under way"
>  >>> x1 = re.compile(r'(dog)(cat)?')
>  >>> rep1 = x1.sub("REPLACE", str1)
>  >>> rep2 = x2.sub("REPLACE", str2)
>  >>> print rep1
> The REPLACE chased the car
>  >>> print rep2
> The REPLACE cat parade was under way
> ...what I'm looking for is a match for the position in front of "Cat", 
> should it exist.

Because my regex says 'look for the word "dog" and remember where you 
found it. If you also find the word "cat", remember that too'. Nowhere 
does it say "watch out for whitespace".

r'(dog)\s*(cat)?' says match 'dog' followed by zero or more whitespace 
(spaces, tabs, etc.) and maybe 'cat'.

There is a wonderful O'Reilly book called "Mastering Regular 
Expressions" or as Danny points out the AMK howto is good.

More information about the Tutor mailing list