Python's regular expression help

Dodo dodo_do_not_wake_up at yahoo.Fr
Thu Apr 29 14:22:16 EDT 2010


Le 29/04/2010 20:00, goldtech a écrit :
> 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'
>
> 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

for multiline, I use re.DOTALL

I do not know match(), findall is pretty efficient :
my = "<a href=\"hello world.com\">LINK</a>"
res = re.findall(">(.*?)<",my)
 >>> res
['LINK']

Dorian



More information about the Python-list mailing list