![](/img/trans.png)
[英]python list of strings, replace all occurences not belonging to a specific sublist
[英]Problem to replace all strings in a line which have a specific pattern in 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 中使用 obj
在 perl 中,它是簡單的一行正則表達式
=~ 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.