Why do look-ahead and look-behind have to be fixed-width patterns?

Steven Bethard steven.bethard at gmail.com
Fri Jan 28 02:13:47 EST 2005


John Machin wrote:
> To grab the text after the 2nd colon (if indeed there are two or more),
> it's much simpler to do this:
> 
>>>>import re
>>>>q = re.compile(r'.*?:.*?:(.*)').search
>>>>def grab(s):
> 
> ...    m = q(s)
> ...    if m:
> ...       print m.group(1)
> ...    else:
> ...       print 'not found!'
> ...
> 
>>>>grab('')
> not found!
> 
>>>>grab('::::')
> ::
> 
>>>>grab('a:b:yadda')
> yadda
> 
>>>>>>>grab('a:b:c:d')
> c:d
> 
>>>>grab('a:b:')
> 
> 

Or without any regular expressions:

py> def grab(s):
...     try:
...         first, second, rest = s.split(':', 2)
...         print rest
...     except ValueError:
...         print 'not found!'
...
py> grab('')
not found!
py> grab('a:b:yadda')
yadda
py> grab('a:b:c:d')
c:d
py> grab('a:b:')

py>

To the OP: what is it you're trying to do?  Often there is a much 
cleaner way to do it without regular expressions...

Steve



More information about the Python-list mailing list