从re.sub.调用函数

use*_*464 15 python regex windows function

这是一个简单的例子:

import re

math='<m>3+5</m>'
print re.sub(r'<(.)>(\d+?)\+(\d+?)</\1>', int(r'\2') + int(r'\3'), math)
Run Code Online (Sandbox Code Playgroud)

它给了我这个错误:

ValueError: invalid literal for int() with base 10: '\\2'
Run Code Online (Sandbox Code Playgroud)

它发送\\2 而不是35.

为什么?我该如何解决?

Bre*_*arn 27

如果要使用函数,则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 '
Run Code Online (Sandbox Code Playgroud)

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


xda*_*azz 7

你需要使用lambda函数.

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