Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python using result of function for Regular Expression Substitution

Tags:

python

regex

I have a block of text, and for every regex match, I want to substitute that match with the return value from another function. The argument to this function is of course the matched text.

I have been having trouble trying to come up with a one pass solution to this problem. It feels like it should be pretty simple.

like image 803
esiegel Avatar asked Feb 13 '09 21:02

esiegel


1 Answers

Right from the documentation:

>>> def dashrepl(matchobj):
...     if matchobj.group(0) == '-': return ' '
...     else: return '-'
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'
like image 168
oefe Avatar answered Sep 29 '22 01:09

oefe