我有一个像这样的字符串:
text = '''this \sum 1,2 \end is three and \sum 2,3,4 \end is nine'''
我有一个在字符串中添加数字的函数
def add(numbers):
return sum(map(lambda x:int(x), numbers.split(",")))
如何使用正则表达式通过将组传递给 add
函数来替换 '\\sum (.+?)\\end'
的所有实例?
即上面的字符串应该是:
'''this 3 is three and 9 is nine'''
我可以使用 findall
获取 "1,2"
和 "2,3,4"
并添加它们,但是如何做我将它们插回到文本中应该放的地方?也许是 findall
和 split
的组合?在 python 中是否有更直接的方法来做到这一点?
最佳答案
使用 re.sub()
代替 re.findall()
,并使用函数来处理每个组。
函数的返回值用作替换字符串:
re.sub(r'\\sum ([\d,]+) \\end', lambda m: str(add(m.group(1))), text)
lambda
创建一个接受一个参数(即匹配对象)的函数。它返回一个基于数字组的字符串,通过 add()
传递。
演示:
>>> import re
>>> text = '''this \sum 1,2 \end is three and \sum 2,3,4 \end is nine'''
>>> def add(numbers):
... return sum(map(lambda x:int(x), numbers.split(",")))
...
>>> re.sub(r'\\sum ([\d,]+) \\end', lambda m: str(add(m.group(1))), text)
'this 3 is three and 9 is nine'
关于python - 处理正则表达式组中的字符串后替换所有出现的正则表达式组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23791357/