regular expression

Peter Otten __peter__ at web.de
Thu Aug 20 09:56:07 CEST 2009


Pierre wrote:

> I would like to change the string "(1 and (2 or 3))"  by  "(x[1] & (x
> [2] || x[3]))" using regular expression...
> Anyone can help me ?

>>> re.compile(r"(\d+)").sub(r"x[\1]", "(1 and (2 or 3))")
'(x[1] and (x[2] or x[3]))'
>>> re.compile("and|or").sub(lambda m, d={"and":"&", "or":"||"}: 
d[m.group()], _)
'(x[1] & (x[2] || x[3]))'

Peter





More information about the Python-list mailing list