从re.sub调用函数 [英] Call functions from re.sub

查看:286
本文介绍了从re.sub调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的例子:

  import re 

math ='< m> 3 + 5 /'
print re.sub(r'<(。)>(\ d +?)\ +(\ d +?) int(r'\2')+ int(r'\3'),math)

它给了我这个错误:

  ValueError:int()的基数为10的无效字面值:'\\ 2' 

它会发送 \\ 2 3 5



为什么?
如何解决它?

解决方案

如果您想使用 re函数.sub 你需要传递一个函数,而不是表达式。如文档 here ,你的函数应该把匹配对象作为参数,返回替换字符串。您可以使用通常的 .group(n)方法等访问组。例如:

  re.sub((a +)(b +),lambda匹配:{0} as和{ 1} bs.format(
len(match.group(1)),len(match.group(2))
),aaabbaabbbaaaabb)
#输出为'3 as和2 bs 2 as和3 bs 4 as和2 bs'

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


This is a simple example:

import re

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

It gives me this error:

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

It sends \\2 instead of 3 and 5.

Why? How do I solve it?

解决方案

If you want to use a function with re.sub you need to pass a function, not an expression. As documented here, your function should take the match object as an argument and returns the replacement string. You can access the groups with the usual .group(n) methods and so on. An example:

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 '

Note that the function should return strings (since they will be put back into the original string).

这篇关于从re.sub调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆