Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找正则表达式并在一些处理后替换_Python_Regex - Fatal编程技术网

Python 查找正则表达式并在一些处理后替换

Python 查找正则表达式并在一些处理后替换,python,regex,Python,Regex,我知道在Python中,您可以找到并替换为 re.sub('(b)','\\1BB','abc') 但是,如果你想要更多的处理,比如你得到一个位数,然后加上x,你会怎么做呢 在正则表达式匹配模式改变的情况下,我可以使用函数将原始字符串切片粘贴到新字符串中,但最简单的方法是什么 您可以在以下位置调用函数而不是简单的替换字符串: 或者 >>> re.sub('(\d+)', ... lambda x: ' {}+3={} '.format(x.group(1),int(

我知道在Python中,您可以找到并替换为

 re.sub('(b)','\\1BB','abc')
但是,如果你想要更多的处理,比如你得到一个位数,然后加上x,你会怎么做呢


在正则表达式匹配模式改变的情况下,我可以使用函数将原始字符串切片粘贴到新字符串中,但最简单的方法是什么

您可以在以下位置调用函数而不是简单的替换字符串:

或者

>>> re.sub('(\d+)',
...     lambda x: ' {}+3={} '.format(x.group(1),int(x.group(1))+3),
...     'a12c')
'a 12+3=15 c'
def r(m):
    return ' {}+{}={} '.format(m.group(1),m.group(2),
                           int(m.group(1))+int(m.group(2)))

>>> print re.sub('(\d)(\d)',r,'a12c')
'a 1+2=3 c'