这是一个简单的例子:
import re
math='<m>3+5</m>'
print re.sub(r'<(.)>(\d+?)\+(\d+?)</\1>', int(r'\2') + int(r'\3'), math)
它给我这个错误:
ValueError: invalid literal for int() with base 10: '\\2'
它发送 \\2
而不是 3
和 5
。
为什么? 我该如何解决?
最佳答案
如果你想在 re.sub
中使用一个函数,你需要传递一个函数,而不是一个表达式。如记录here ,您的函数应将匹配对象作为参数并返回替换字符串。您可以使用通常的 .group(n)
方法等访问组。一个例子:
re.sub("(a+)(b+)", lambda match: "{0} as and {1} bs ".format(
len(match.group(1)), len(match.group(2))
), "aaabbaabbbaaaabb")
# Output is '3 as and 2 bs 2 as and 3 bs 4 as and 2 bs '
请注意,该函数应返回字符串(因为它们将被放回原始字符串中)。
关于python - 从 re.sub 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11944978/