代码之家  ›  专栏  ›  技术社区  ›  ramaa overseas

替换无法使用str.replacement()的特殊字符[重复]

  •  -1
  • ramaa overseas  · 技术社区  · 2 年前

    我有一个形式为的参数文件:

    parameter-name parameter-value
    

    其中参数可以按任何顺序排列,但每行只有一个参数。我想替换一个参数的 parameter-value 具有新值。

    我正在使用行替换功能 posted previously 替换使用Python的 string.replace(pattern, sub) 。例如,我使用的正则表达式在vim中有效,但在中似乎不起作用 string.replace() .

    以下是我正在使用的正则表达式:

    line.replace("^.*interfaceOpDataFile.*$/i", "interfaceOpDataFile %s" % (fileIn))
    

    哪里 "interfaceOpDataFile" 是我要替换的参数名称(/I表示不区分大小写),新的参数值是 fileIn 变量

    有没有一种方法可以让Python识别这个正则表达式,或者有其他方法可以完成这项任务?

    0 回复  |  直到 7 年前
        1
  •  717
  •   Alan W. Smith vishes_shell    8 年前

    str.replace() v2 | v3 不识别正则表达式。

    若要使用正则表达式执行替换,请使用 re.sub() v2 | v3 .

    例如:

    import re
    
    line = re.sub(
               r"(?i)^.*interfaceOpDataFile.*$", 
               "interfaceOpDataFile %s" % fileIn, 
               line
           )
    

    在循环中,最好先编译正则表达式:

    import re
    
    regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)
    for line in some_file:
        line = regex.sub("interfaceOpDataFile %s" % fileIn, line)
        # do something with the updated line
    
        2
  •  512
  •   Hugo    3 年前

    您正在寻找 re.sub 作用

    import re
    s = "Example String"
    replaced = re.sub('[ES]', 'a', s)
    print(replaced)
    

    将打印 axample atring

        3
  •  20
  •   kpie    11 年前

    作为总结

    import sys
    import re
    
    f = sys.argv[1]
    find = sys.argv[2]
    replace = sys.argv[3]
    with open (f, "r") as myfile:
         s=myfile.read()
    ret = re.sub(find,replace, s)   # <<< This is where the magic happens
    print ret
    
        4
  •  11
  •   Nelz11    13 年前

    re.sub 绝对是你想要的。所以你知道,你不需要锚和通配符。

    re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)
    

    会做同样的事情——匹配第一个看起来像“interfaceOpDataFile”的子字符串并替换它。