简体   繁体   English

Python使用正则表达式替换函数的结果

[英]Python using result of function for Regular Expression Substitution

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. 感觉它应该很简单。

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'

Python-agnostic: Match everything before and everything after your text to replace. Python-agnostic:匹配文本之前和之后的所有内容。

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

Then you have the next before and after the text you're going to replace. 然后你将在要替换的文本之前和之后有下一个。 The rest is easy -- just insert the result of your function between the two strings. 其余的很简单 - 只需在两个字符串之间插入函数的结果即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM