0

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

例如:

原始字符串:

这是123,那是ABC。

这是 456,也就是 OPQ。

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

结果是对列表,例如:

123:那是XYZ,那是ABC。

456:那是XYZ,那是OPQ。

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

是否可以使用 Regex 在 Python 中执行此操作?

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

谢谢你的回答。

4

4 回答 4

2

像这样的东西?

>>> 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.'
于 2013-06-20T10:42:18.550 回答
1
string = "This is 123 and that is ABC."
match = re.search("\d+", string).group()
string = match+":"+string.replace(match, "XYZ")

考虑到比赛肯定会发生,否则你可以在比赛周围加上一个 if 条件

于 2013-06-20T11:00:49.267 回答
0

它可能是这样的:

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

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

于 2013-06-20T10:50:33.463 回答
0

我的首选方法是使用替换功能

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

re.sub('This is (\d+)', f, strs)
于 2013-06-20T10:56:53.097 回答