Help with regular expression

anton muhin antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Thu Sep 18 05:11:40 EDT 2003


Stephen Boulet wrote:

> I'm trying to write an RE to match a string that might or might not be 
> ther and everything past it up to another string that might or might not 
> be there and everything past it to a third string that might or might 
> not be there and everything past it.
> 
> Say my strings are "STRING1", "STRING2", and "String3".
> 
> Would the re be:
> 
>    r'((STRING1.*)(STRING2.*)(STRING3.*))'
> 
> The goal is to separate the groups by newlines, but I only want the 
> first group to match up to the second group and the second to match up 
> to the third.
> 
> Normally I would achieve this by typing:
> 
>    pat = re.compile(r'((STRING1.*)(STRING2.*)(STRING3.*))')
>    m = pat.findall(s)
>    s = '\n\n'.join(m[0])
> 
> but the first group would seem to match everything.
> 
> How can I get it to do what I want?
> 
> -- Stephen
> 

Try non-greedy wildcards: r'((STRING1.*?)(STRING2.*?)(STRING3.*?))'
				       -           -           -

should do the trick.

hth,
anton.





More information about the Python-list mailing list