Python's regular expression help

MRAB python at mrabarnett.plus.com
Thu Apr 29 14:43:23 EDT 2010


goldtech wrote:
> Hi,
> Trying to start out with simple things but apparently there's some
> basics I need help with. This works OK:
>>>> import re
>>>> p = re.compile('(ab*)(sss)')
>>>> m = p.match( 'absss' )
>>>> m.group(0)
> 'absss'
>>>> m.group(1)
> 'ab'
>>>> m.group(2)
> 'sss'
> ...
> But two questions:
> 
> How can I operate a regex on a string variable?
> I'm doing something wrong here:
> 
>>>> f=r'abss'
>>>> f
> 'abss'
>>>> m = p.match( f )
>>>> m.group(0)
> Traceback (most recent call last):
>   File "<pyshell#15>", line 1, in <module>
>     m.group(0)
> AttributeError: 'NoneType' object has no attribute 'group'
> 
Look closely: the regex contains 3 letter 's', but the string referred
to by f has only 2.

> How do I implement a regex on a multiline string?  I thought this
> might work but there's problem:
> 
>>>> p = re.compile('(ab*)(sss)', re.S)
>>>> m = p.match( 'ab\nsss' )
>>>> m.group(0)
> Traceback (most recent call last):
>   File "<pyshell#26>", line 1, in <module>
>     m.group(0)
> AttributeError: 'NoneType' object has no attribute 'group'
> 
> Thanks for the newbie regex help, Lee

The string contains a newline between the 'b' and the 's', but the regex
isn't expecting any newline (or any other character) between the 'b' and
the 's', hence no match.



More information about the Python-list mailing list