Python正则表达式:如何一次替换并返回匹配项?

Python正则表达式:如何一次替换并返回匹配项?,python,regex,Python,Regex,我想替换字符串中的所有匹配项,并获取匹配项数组 以下是如何使用两个功能完成此操作: str = "foo123bar456" nums = re.findall(r'\d+', str) str = re.sub(r'\d+', '', str) 但这不必要地经历了两次。如何一次性完成此操作?在re.sub中,参数repl可以是返回字符串的函数。我们可以使用此选项将匹配项添加到列表中: import re def substitute(string): def _sub(m

我想替换字符串中的所有匹配项,并获取匹配项数组

以下是如何使用两个功能完成此操作:

str = "foo123bar456"
nums = re.findall(r'\d+', str)
str = re.sub(r'\d+', '', str)    

但这不必要地经历了两次。如何一次性完成此操作?

re.sub
中,参数
repl
可以是返回字符串的函数。我们可以使用此选项将匹配项添加到列表中:

import re


def substitute(string):
    def _sub(match):
        matches.append(match)
        return ''

    matches = []
    new_string = re.sub(r'\d+', _sub, string)
    return new_string, matches


print(substitute('foo123bar456'))
> ('foobar', [<_sre.SRE_Match object; span=(3, 6), match='123'>, <_sre.SRE_Match object; span=(9, 12), match='456'>])
重新导入
def替换(字符串):
def_接头(匹配):
匹配。追加(匹配)
返回“”
匹配项=[]
新的_字符串=re.sub(r'\d+',_sub,字符串)
返回新的\u字符串,匹配项
打印(替换('foo123bar456'))
>('foobar',[,])

re.sub
中,参数
repl
可以是返回字符串的函数。我们可以使用此选项将匹配项添加到列表中:

import re


def substitute(string):
    def _sub(match):
        matches.append(match)
        return ''

    matches = []
    new_string = re.sub(r'\d+', _sub, string)
    return new_string, matches


print(substitute('foo123bar456'))
> ('foobar', [<_sre.SRE_Match object; span=(3, 6), match='123'>, <_sre.SRE_Match object; span=(9, 12), match='456'>])
重新导入
def替换(字符串):
def_接头(匹配):
匹配。追加(匹配)
返回“”
匹配项=[]
新的_字符串=re.sub(r'\d+',_sub,字符串)
返回新的\u字符串,匹配项
打印(替换('foo123bar456'))
>('foobar',[,])

re.sub
中使用lambda函数:

>>> str = "foo123bar456"
>>> arr=[]
>>> print re.sub(r'(\d+)', lambda m: arr.append(m.group(1)), str)
foobar
>>> print arr
['123', '456']

re.sub
中使用lambda函数:

>>> str = "foo123bar456"
>>> arr=[]
>>> print re.sub(r'(\d+)', lambda m: arr.append(m.group(1)), str)
foobar
>>> print arr
['123', '456']