Python using function result to replace expression regularly

I have a block of text, and for each regular expression I want to substitute this correspondence with the return value from another function. The argument for this function is, of course, a consistent text.

I am having trouble trying to come up with a one-pass solution to this problem. It seems like it should be pretty simple.

+5
source share
2 answers

To the right of the documentation :

>>> def dashrepl(matchobj):
...     if matchobj.group(0) == '-': return ' '
...     else: return '-'
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'
+14
source

Python-agnostic: match everything before and after a word after a replacement.

/^(.*?)(your regexp to match)(.*)$/

, . - .

0

All Articles