Call functions from re.sub

后端 未结 2 950
独厮守ぢ
独厮守ぢ 2020-12-31 05:07

This is a simple example:

import re

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


        
相关标签:
2条回答
  • 2020-12-31 05:50

    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).

    0 讨论(0)
  • 2020-12-31 06:04

    You need to use lambda function.

    print re.sub(r'<(.)>(\d+?)\+(\d+?)</\1>', lambda m: str(int(m.group(2)) + int(m.group(3))), math)
    
    0 讨论(0)
提交回复
热议问题