Help needed: cryptic perl regular expression in python syntax

pekka niiranen pekka.niiranen at wlanmail.com
Tue Oct 19 14:19:19 CEST 2004


Hi there,

I have perl script that uses dynamically
constructed regular in this way:

------perl code starts ----
$result "";
$key = AAA\?01;
$key = quotemeta $key;
$line = "   s^\?AAA\?01^BBB^g; #Comment "
if ($line =~ /(^\s*)(s|tr)(.)(\\?\??$key\??)\3(.*?)\3(.*)/) {
	$result = $5;

# $result should be "BBB"
# \3 gets the same value as returned by (.)
# which is in this example ^. So we are searching
# parameter limited by first two ^-signs
# and returning the one limited byt the second
# and third ^-sign. Note that using \3 in regular
# expression enables other constants used than ^ -sign.

------perl code stops ----

How can I construct equivalent python regural expression ?

I have tested with constant regular expression like this:

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

Which is fine, but is there a way to join 3 raw strings
together into another raw strings? like:

r1 = r'''(^\s*)(s|tr)(.)(\\?\??'''
r2 = r'''\\?\??)\3(.*?)\3(.*)'''
p1 = r1 + key + r2 # p1 should remain raw string too

-pekka-





More information about the Python-list mailing list