variable in regexp

Lee Harr missive at frontiernet.net
Sat Aug 30 18:51:19 EDT 2003


In article <mailman.1062264196.30038.python-list at python.org>, Peter Enis wrote:
> hello,
> 
> does anyone know how to use variables in regular expressions?
> 
> var = '%%bob%%'
> 
> replace = 'bob'
> 
> var = re.sub("%%[^%%]*replace%%', 'peter', var)
> 
> how do i have to mask the replace-variable?
> 


I am not exactly sure what you want to do, but you can
make the replace argument to .sub() a function... ie:

def repl(matchobj):
    # do stuff w/ matchobj here
    return 'foo'

var = re.sub(repl, 'peter', var)





More information about the Python-list mailing list