搜索包含一些文本的行,替换完整的行python

时间:2011-10-18 19:24:48

标签: python regex replace

所以我试图搜索某个字符串,例如可能是: process.control.timeout = 30,但30可以是任何东西。我试过这个:

for line in process:
    line = line.replace("process.control.timeout", "process.control.timeout=900")
    outFile.write(line)

但这会让我回到process.control.timeout = 900 = 30。我有一种感觉,我需要使用带有通配符的正则表达式?但我对python很新。

3 个答案:

答案 0 :(得分:4)

没有正则表达式:

for line in process:
    if "process.control.timeout" in line:
        # You need to include a newline if you're replacing the whole line
        line = "process.control.timeout=900\n" 
    outFile.write(line)

outFile.writelines("process.control.timeout=900\n" 
                      if "process.control.timeout" in line else line 
                         for line in process)

如果您匹配的文字位于该行的开头,请使用line.startswith("process.control.timeout")代替"process.control.timeout" in line

答案 1 :(得分:1)

你是对的,正则表达式是要走的路。

import re
pattern = re.compile(r"process\.control\.timeout=\d+")
for line in process:
    line = pattern.sub("process.control.timeout=900", line)
    outFile.write(line)

答案 2 :(得分:0)

这可能是你想要的(匹配==之后的数字是可选的)。当您在循环中搜索和替换时,单独编译正则表达式比直接使用re.sub更有效。

import re

pattern = re.compile(r'process\.control\.timeout(=\d+)?')

for line in process:
    pattern.sub('process.control.timeout=900', line)