简体   繁体   English

Python正则表达式替换文件中的行

[英]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. 我有一个快速且肮脏的构建脚本,需要在一个小的xml配置文件中更新几行。 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: 我有2个问题:

  • 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. 例如,我没有获得<version>abc</version> ,而是获得了由控制字符包围的版本值。 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. 当我将行写回到文件( print line )时,我得到了几个额外的换行符。

What am I borking up here? 我在这烦吗?

Try to replace "\\1%s\\2" by "\\g<1>%s\\g<2>" , it might be the problem.. 尝试将"\\1%s\\2" by "\\g<1>%s\\g<2>"替换"\\1%s\\2" by "\\g<1>%s\\g<2>" ,这可能是问题所在。

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 您可以尝试: print line,并用逗号来抑制新行char

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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