【问题标题】:Python string.replace regular expression [duplicate]Python string.replace 正则表达式 [重复]
【发布时间】:2013-05-19 04:52:47
【问题描述】:

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

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 识别这个正则表达式,或者有没有其他方法可以完成这个任务?

【问题讨论】:

    标签: python regex replace


    【解决方案1】:

    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
    

    【讨论】:

    • 我必须将flags=re.MULTILINE 作为re.sub 的最后一个参数传入才能使其工作,这是有道理的 - read about it in the docs here
    • 正则表达式编译被缓存(docs),因此甚至不需要编译。但正如您所展示的,如果编译,则在循环外编译。
    • 想知道是否编译的详细信息,请查看this answer
    【解决方案2】:

    您正在寻找re.sub 函数。

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

    将打印axample atring

    【讨论】:

    • 是否可以在一行中用大小写替换,例如如果第一个字符是 E 更改为 G,如果 Z 将其更改为 B。
    • 你可以传递一个字符串 -> 字符串函数作为re.sub的第二个参数。将使用每个匹配的子字符串调用该函数,并将其结果放入结果中。
    • 如果我们想要不区分大小写的替换,我们可以输入replaced = re.sub('[ES]', 'a', s, flags=re.IGNORECASE)
    • 在搜索表达式前使用 r 时?
    • @Timo Regex 通常包含反斜杠,不应“被 Python”转义。 stackoverflow.com/a/2081708/6371758
    【解决方案3】:

    总结一下

    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】:

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

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

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

      【讨论】:

      • 我需要替换整行,因为原始文件将具有类似:interfaceOpDataFile SomeDummyFile.txt 并且我想将其替换为:interfaceOpDataFile SomeUsefulFile.txt 如果我不包括锚点,将如何替换知道我想摆脱SomeDummyFile.txt吗?
      • 啊,我完全误解了您对替换的操作。如果每一对都在自己的行上,你仍然不需要明确的锚点。 re.sub(r"(?i)(interfaceOpDataFile).*", r'\1 UsefulFile', line) 这将占用整行,捕获争论名称,并将其添加回您的替换。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 2012-07-13
      • 2019-01-25
      相关资源
      最近更新 更多