Python Regular Expressions: re.sub(regex, replacement, subject)

Steven Bethard steven.bethard at gmail.com
Tue Jul 5 12:33:39 EDT 2005


Vibha Tripathi wrote:
> In the Python re.sub(regex, replacement, subject)
> method/function, I need the second argument
> 'replacement' to be another regular expression ( not a
> string) . So when I find a 'certain kind of string' in
> the subject, I can replace it with 'another kind of
> string' ( not a predefined string ). Note that the
> 'replacement' may depend on what exact string is found
> as a result of match with the first argument 'regex'.
> 
> Please let me know if the question is not clear.

It's still not very clear, but my guess is you want to supply a 
replacement function instead of a replacement string, e.g.:

py> help(re.sub)
Help on function sub in module sre:

sub(pattern, repl, string, count=0)
     Return the string obtained by replacing the leftmost
     non-overlapping occurrences of the pattern in string by the
     replacement repl.  repl can be either a string or a callable;
     if a callable, it's passed the match object and must return
     a replacement string to be used.

py> def repl(match):
...     print match.group()
...     return '46'
...
py> re.sub(r'x.*?x', repl, 'yxyyyxxyyxyy')
xyyyx
xyyx
'y4646yy'

STeVe



More information about the Python-list mailing list