简体   繁体   中英

Python regex to replace line in file

I have a quick and dirty build script that needs to update a couple of lines in a small xml config file. Since the file is so small, I'm using an admittedly inefficient process to update the file in place just to keep things simple:

def update_xml(property, value):
  for line in fileinput.input(os.path.join(app_dir, 'my.xml'), inplace=True):
    if property is 'version':
      line = re.sub(r'(<version>).*?(</version>)', '\1%s\2' % value, line, flags=re.IGNORECASE)
    elif property is 'brand':
      line = re.sub(r'(<property name="brand" type="string">).*?(</property>)', '\1%s\2' % value, line, flags=re.IGNORECASE)
    elif property is 'env':
      line = re.sub(r'(<property name="env" type="string">).*?(</property>)', '\1%s\2' % value, line, flags=re.IGNORECASE)

    print line

I have 2 problems:

  • The back references aren't capturing what I expect. Instead of getting <version>abc</version> , for example, I get the version value surrounded by control characters. I've tried doubling up the backslash, removing the formatted print and a couple of other things, but can't get it quite right.
  • When I write the line back to the file ( print line ), I get several extra line breaks.

What am I borking up here?

Try to replace "\\1%s\\2" by "\\g<1>%s\\g<2>" , it might be the problem..

About the newlines , the print might be adding a second new line on top of the existing one .

you can try: print line, with a comma to suppress the new line char

使用原始字符串以避免\\1\\2成为控制字符: r'\\1%s\\2'

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