Help needed: cryptic perl regular expression in python syntax, Ugly solution

Steven Bethard steven.bethard at gmail.com
Wed Oct 20 08:22:15 CEST 2004


Pekka Niiranen <pekka.niiranen <at> wlanmail.com> writes:
> 
> I managed to solve my problem with code like this:
>  >>> line = '   s^\\?AAA\\?01^BBB^g; #Comment '
>  >>> r1 = '(^\\s*)(s|tr)(.)(\\\\\\?\\\\??'
>  >>> key = "AAA\?01"
>  >>> r2 = '\\\\??)\\3(.*?)\\3(.*)'
>  >>> r = r1 + re.escape(key) + r2
>  >>> re.compile(r).findall(line)
> [('   ', 's', '^', '\\?AAA\\?01', 'BBB', 'g; #Comment ')]


Could you do something like:

>>> line = '   s^\\?AAA\\?01^BBB^g; #Comment '
>>> expr = r'(^\s*)(s|tr)(.)(\\\?%s)\3(.*?)\3(.*)'
>>> matcher = re.compile(expr % re.escape("AAA\?01"))
>>> matcher.findall(line)
[('   ', 's', '^', '\\?AAA\\?01', 'BBB', 'g; #Comment ')]

Basically, I still use the r'' string so that I don't have to write so many 
backslashes, but then I use a %s to insert the "AAA\?01" into the middle of 
the expression.  Looks at least a little cleaner to me.

Steve




More information about the Python-list mailing list