python - 从 re.sub 调用函数

标签 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)

它给我这个错误:

ValueError: invalid literal for int() with base 10: '\\2'

它发送 \\2 而不是 35

为什么? 我该如何解决?

最佳答案

如果你想在 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/

相关文章:

python - 有没有一种方法可以将我自己的 CLI 开关传递给单元测试文件?

python - pandas 保留满足或失败条件的两行

regex - 带有嵌套 .htaccess 文件的 mod_rewrite

ruby - 如何从 Ruby 脚本以编程方式启动 Rails 服务器

python - Windows shell %ERRORLEVEL% 变量是否有字符限制?

python - 在 Linux 上安装 cx_Oracle 时出现问题 - 导入仅适用于站点包目录

python - setuptools 包上的 Pyinstaller

python - 在 Windows 上查找当前 wifi 网络的名称

php - 匹配元标记的正则表达式

regex - 如何在 .htaccess 中使用正则表达式转义 "?"for mod_rewrite