简体   繁体   中英

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

I have a file with the following lines:

 [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;

and I'm trying to write an expression in python that would allow me to find all the lines that contain the "[Path('*')]" pattern and replace the last square bracket with ", RolesAllowed('admin')]". However, I'm having trouble coming up with the correct regular expression to achieve this, this is what I have so far but it isn't working:

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

I'm entirely new to regular expressions, any help is appreciated, thanks!

You need to escape all regex control characters in your pattern, test here :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM