在Python正则表达式中,在替换之前获取值

在Python正则表达式中,在替换之前获取值,python,regex,Python,Regex,在使用正则表达式用Python中的其他值替换字符串之前,我想从字符串中获取值,但我不知道如何做 例如: 原始字符串: 这是123,那是ABC 这是456,这是OPQ 我想提取123和456,然后将“This is 123”和“This is 456”替换为“That was XYZ” 结果是成对列表,例如: 123:那是XYZ,那是ABC 456:那是XYZ,那是OPQ 上面是一个非常简单的例子,在我的例子中,提取和替换的字符串可能更复杂 是否可以使用正则表达式在Python中执行此操作 我最初

在使用正则表达式用Python中的其他值替换字符串之前,我想从字符串中获取值,但我不知道如何做

例如:

原始字符串:

这是123,那是ABC

这是456,这是OPQ

我想提取123和456,然后将“This is 123”和“This is 456”替换为“That was XYZ”

结果是成对列表,例如:

123:那是XYZ,那是ABC

456:那是XYZ,那是OPQ

上面是一个非常简单的例子,在我的例子中,提取和替换的字符串可能更复杂

是否可以使用正则表达式在Python中执行此操作

我最初的想法是使用re.findall查找所有数字,然后使用sub替换字符串。但问题是,我不确定是否有可能将替换的字符串与数字配对

谢谢你的回答。

像这样的吗

>>> strs = "This is 123 and that is ABC."
>>> match = re.search(r'.*?(\d+)',strs)
>>> rep = match.group(0)
>>> num = match.group(1)
>>> "{}: {}".format(num, re.sub(rep,'That was XYZ',strs))
'123: That was XYZ and that is ABC.'

>>> strs = 'This is 456 and that is OPQ.'
>>> match = re.search(r'.*?(\d+)',strs)
>>> rep = match.group(0)
>>> num = match.group(1)
>>> "{}: {}".format(num, re.sub(rep,'That was XYZ',strs))
'456: That was XYZ and that is OPQ.'
像这样的

>>> strs = "This is 123 and that is ABC."
>>> match = re.search(r'.*?(\d+)',strs)
>>> rep = match.group(0)
>>> num = match.group(1)
>>> "{}: {}".format(num, re.sub(rep,'That was XYZ',strs))
'123: That was XYZ and that is ABC.'

>>> strs = 'This is 456 and that is OPQ.'
>>> match = re.search(r'.*?(\d+)',strs)
>>> rep = match.group(0)
>>> num = match.group(1)
>>> "{}: {}".format(num, re.sub(rep,'That was XYZ',strs))
'456: That was XYZ and that is OPQ.'

可能是这样的:

In [1]: s = 'This is 123 and that is ABC.'

In [2]: patt = re.compile('This is (?P<number>\d+)')

In [3]: patt.findall(s)
Out[3]: ['123']

In [4]: patt.sub('That was XYZ', s)
Out[4]: 'That was XYZ and that is ABC.'
[1]中的
s='这是123,那是ABC。'
在[2]中:patt=re.compile('This is(?P\d+))
在[3]中:帕特·芬德尔(s)
Out[3]:['123']
在[4]中:patt.sub('那是XYZ',s)
Out[4]:“那是XYZ,那是ABC。”

然后,您可以将其包装成一个简单的函数,该函数返回带有数字和替换字符串的元组。

它可能类似于:

In [1]: s = 'This is 123 and that is ABC.'

In [2]: patt = re.compile('This is (?P<number>\d+)')

In [3]: patt.findall(s)
Out[3]: ['123']

In [4]: patt.sub('That was XYZ', s)
Out[4]: 'That was XYZ and that is ABC.'
[1]中的
s='这是123,那是ABC。'
在[2]中:patt=re.compile('This is(?P\d+))
在[3]中:帕特·芬德尔(s)
Out[3]:['123']
在[4]中:patt.sub('那是XYZ',s)
Out[4]:“那是XYZ,那是ABC。”

然后,您可以将其包装成一个简单的函数,该函数返回带有数字和替换字符串的元组。

我首选的方法是使用替换函数

def f(match):
    print match.group(1)
    return 'That was XYZ'

re.sub('This is (\d+)', f, strs)

我的首选方法是使用replace函数

def f(match):
    print match.group(1)
    return 'That was XYZ'

re.sub('This is (\d+)', f, strs)
考虑到比赛肯定会发生,否则你可以在比赛前后设置一个if条件


考虑到匹配确实会发生,否则您可以在匹配周围设置if条件

请选择一个更好的示例,我假设您的实际代码使用regexp请选择一个更好的示例,我假设您的实际代码使用regexp,除非
re.sub
计数为
1
,您应该使用
re.findall
而不是
re.search
除非
re.sub
计数为
1
,否则您应该使用
re.findall
而不是
re.search