替换python中具有特定模式的一行中的所有字符串的问题



让我先说一下,我是python的新手。

line = "lmn = abc(xyz)/123/.../abc(123)"
line = "abc(xyz) = dlf/hmn/abc(fdg)"

我正在尝试的模式替换示例是abc(xxx) = $xxx沿着这些行。

我创建的正则表达式是(abc()(.*?)())——>这工作得很好。现在我如何确保替换发生在一行中的所有位置,因为(.*?)在一行的不同位置是不同的。

我发现我们有re.findall(pattern, string, flags=0),它将返回一个元组,我可以用它来构建一个表并进行行替换。有没有更好的方法来替换所有的模式?

tmp = re.sub('(abc\()(.*?)(\))', '$' **group(1) content**, line , count=???)

上面的问题是我不能在我调用

的re.sub中使用对象。在perl中很简单,只有一行regex

=~ s/(abc\()(.*?)(\))/(\$)$2/g

你能告诉我一个文件的模块或任何正则表达式模块在python,我可以使用这个。顺便说一句,我正在使用python 3.6

您可以在sub的替换模式中使用<capture group number>来插入一个捕获组。

如果我正确理解了你的问题,这就是你要找的:

import re
line1 = "lmn = abc(xyz)/123/.../abc(123)"
line2 = "abc(xyz) = dlf/hmn/abc(fdg)"
# I've simplified the pattern a little to only use two capture groups.
pattern = re.compile(r"(abc((.*?)))")
# This is the pattern to replace with: a dollar sign followed by the
# contents of capture group 2.
replacement_pattern = r"$2"
print(pattern.sub(replacement_pattern, line1)) # lmn = $xyz/123/.../$123
print(pattern.sub(replacement_pattern, line2)) # $xyz = dlf/hmn/$fdg

最新更新