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()

我对正则表达式完全陌生,感谢任何帮助,谢谢!

您需要转义模式中的所有正则表达式控制字符,测试 here:

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