【问题标题】:Call functions from re.sub从 re.sub 调用函数
【发布时间】:2014-06-02 17:10:29
【问题描述】:

这是一个简单的例子:

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

为什么? 我该如何解决?

【问题讨论】:

标签: python regex windows function


【解决方案1】:

如果你想通过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 '

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

【讨论】:

    【解决方案2】:

    你需要使用 lambda 函数。

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

    【讨论】:

    • 虽然只是个例子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 2013-09-15
    • 2019-05-19
    • 2020-12-18
    • 2017-03-05
    • 2011-07-01
    • 1970-01-01
    相关资源
    最近更新 更多