[英]Problem to replace all strings in a line which have a specific pattern in python
Let me start by saying that i am new to python.首先让我说我是 python 新手。
line = "lmn = abc(xyz)/123/.../abc(123)"
line = "abc(xyz) = dlf/hmn/abc(fdg)"
The pattern replacement example I am trying is abc(xxx) = $xxx
something along these lines.我正在尝试的模式替换示例是
abc(xxx) = $xxx
类似的东西。
The regex I have created is (abc\()(.*?)(\))
--> this is working fine.我创建的正则表达式是
(abc\()(.*?)(\))
--> 这工作正常。 Now how do I ensure the replacement happens in all the places in a line as the (.*?)
is different at different places in a line.现在我如何确保替换发生在一行中的所有位置,因为
(.*?)
在一行中的不同位置是不同的。
I found that we have re.findall(pattern, string, flags=0)
which will return a tuple which I can use to construct a table and go with line replacing.我发现我们有
re.findall(pattern, string, flags=0)
它将返回一个元组,我可以用它来构造一个表并进行行替换。 Is there a better way of substituting the pattern everywhere?有没有更好的方法来替换所有地方的模式?
tmp = re.sub('(abc\\()(.*?)(\\))', '$' **group(1) content**, line , count=???)
The problem with above is I cant use the obj within the re.sub I call上面的问题是我不能在我调用的 re.sub 中使用 obj
in perl it was simple one line regex在 perl 中,它是简单的一行正则表达式
=~ s/(abc\\()(.*?)(\\))/(\\$)$2/g
Can you please point me to a document for a module or any regex module in python that I can use for this.能否请您指向我可以用于此的模块或 python 中的任何正则表达式模块的文档。 Btw..I am using python 3.6
顺便说一句..我正在使用 python 3.6
You can use \<capture group number>
in the replacement pattern for sub
to insert a capture group.您可以在
sub
的替换模式中使用\<capture group number>
来插入捕获组。
So if I'm understanding your question correctly, this is what you're looking for:因此,如果我正确理解您的问题,这就是您要查找的内容:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.