从 re.sub 调用函数



这是一个简单的例子:

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而不是35

为什么?我该如何解决?

如果要

将函数与re.sub一起使用,则需要传递函数,而不是表达式。 如此处所述,您的函数应将 match 对象作为参数并返回替换字符串。 您可以使用常用的.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 '

请注意,该函数应返回字符串(因为它们将被放回原始字符串中)。

你需要使用 lambda 函数。

print re.sub(r'<(.)>(d+?)+(d+?)</1>', lambda m: str(int(m.group(2)) + int(m.group(3))), math)

最新更新