簡體   English   中英

Python 使用正則表達式替換文件中匹配特定格式的行

[英]Python replace lines in a file that match a certain format using regex

我有一個包含以下幾行的文件:

 [Path('info')]
TInfoResource = class
 protected
 public
  [GET, Path('/build/'), Produces(TMediaType.TEXT_PLAIN)]
  function GetBuild: string;
  [GET, Path('/version/'), Produces(TMediaType.TEXT_PLAIN)]
  function GetVersion: string;
 end;

 [Path('helloworld')]
  THelloWorldResource = class
  protected
  public
    [GET, Produces(TMediaType.TEXT_PLAIN)]
    function SayHelloWorld: string;
  end;

我正在嘗試在 python 中編寫一個表達式,這將允許我找到包含“[Path('*')]”模式的所有行並將最后一個方括號替換為“, RolesAllowed('admin')] ”。 但是,我在想出正確的正則表達式來實現這一點時遇到了麻煩,這是我到目前為止所擁有的,但它不起作用:

filename = "RAsistance"

#input file
fin = open(filename + ".pas", "rt")
fout = open(filename + "_MOD.pas", "wt")
for line in fin:
    if (re.search(r"^\[Path (*) \]", line)):
        fout.write(line.replace(']', ", RolesAllowed('admin')]"))

fin.close()
fout.close()

我對正則表達式完全陌生,感謝任何幫助,謝謝!

您需要轉義模式中的所有正則表達式控制字符,在這里測試:

^\[Path\s{0,}\(['*]+\)\s{0,}\]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM