替换在Python中具有特定模式的行中所有字符串的问题
首先,我说我是Python的新手。
line = "lmn = abc(xyz)/123/.../abc(123)"
line = "abc(xyz) = dlf/hmn/abc(fdg)"
我正在尝试的模式替换示例是abc(xxx)= $ xxx
与这些行相符。
我创建的正则是(abc \()(。*?)(\))
- >这很好。 现在,如何确保替换发生在一行中的所有位置,因为(。*??)
在行的不同位置有所不同。
我发现我们有re.findall(模式,字符串,flags = 0)
,它将返回一个元组,我可以用来构建表并替换行。 是否有更好的方式可以替代各地的模式?
tmp = re.sub('(abc\\()(.*?)(\\))', '$' **group(1) content**, line , count=???)
上面的问题是我无法在re.sub中使用obj。我称之为
perl,这很简单,一行正则
=~ s/(abc\\()(.*?)(\\))/(\\$)$2/g
是我可以将我指向一个模块或python中的任何python的文档。顺便说一句..我正在使用Python 3.6
Let me start by saying that i am new to 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.
The regex I have created is (abc\()(.*?)(\))
--> this is working fine.
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.
Is there a better way of substituting the pattern everywhere?
tmp = re.sub('(abc\\()(.*?)(\\))', '
The problem with above is I cant use the obj within the re.sub I call
in perl it was simple one line regex
=~ 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. Btw..I am using python 3.6
**group(1) content**, line , count=???)
The problem with above is I cant use the obj within the re.sub I call
in perl it was simple one line regex
Can you please point me to a document for a module or any regex module in python that I can use for this. Btw..I am using python 3.6
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在
sub
的替换模式中使用\<捕获组号
来插入捕获组。因此,如果我正确理解您的问题,这就是您要寻找的:
You can use
\<capture group number>
in the replacement pattern forsub
to insert a capture group.So if I'm understanding your question correctly, this is what you're looking for: