Python's RE
John Mitchell
johnm at magnet.com
Mon Jun 5 14:53:25 EDT 2000
On Mon, 5 Jun 2000, Jerome Quelin wrote:
> Python does not support non-greedy quantifiers (ie, *?, +? and {,}?)... In
> fact, Perl is the only language that does, I think. You are to do it another
> way in Python.
>
> > print re.search(r'\((.+?)\)',
> >'aaa(foo)bbb(bar)asdfsadf',re.S|re.M).groups()
> Replace the (.+?) part of your regexp with ([^)]+) and it should work
> the way I think you want it to work
I'm pretty sure you're wrong, Python *does* support the non-greedy '+'
operator. In Python 1.5.1:
>>> import re
>>> x=re.compile('a.+?b')
>>> p=x.match('axxxb awoob')
>>> p.group(0)
'axxxb'
The non-greedy ".+?" matches only up to the *first* "b", not the last.
Here's the greedy version:
>>> re.compile('a.+b').match('axxxb awoob').group(0)
'axxxb awoob'
I'd highly recommend switing to non-greedy operators, it's extremly
useful. Regular expressions tend to be pretty hairy, and using this and
inline comments helps tremendously.
- j
"The opposite of bravery is not cowardice but conformity."
--Robert Anthony
More information about the Python-list
mailing list