[英]Search for a line that contains some text, replace complete line python
So I am trying to search for a certain string which for example could be: process.control.timeout=30, but the 30 could be anything. 因此,我尝试搜索某个特定的字符串,例如:process.control.timeout = 30,但30可以是任何字符串。 I tried this: 我尝试了这个:
for line in process:
line = line.replace("process.control.timeout", "process.control.timeout=900")
outFile.write(line)
But this will bring me back process.control.timeout=900=30. 但这会带我回去process.control.timeout = 900 = 30。 I have a feeling I will need to use regex with a wildcard? 我觉得我需要将正则表达式与通配符一起使用? But I'm pretty new to python. 但是我对python很陌生。
Without regex: 没有正则表达式:
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)
or 要么
outFile.writelines("process.control.timeout=900\n"
if "process.control.timeout" in line else line
for line in process)
If the text you're matching is at the beginning of the line, use line.startswith("process.control.timeout")
instead of "process.control.timeout" in line
. 如果您要匹配的文本在行的开头,请在line中使用line.startswith("process.control.timeout")
而不是"process.control.timeout" in line
。
You are correct, regex is the way to go. 您是对的,正则表达式是解决之道。
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)
This is probably what you want (matching =
and digits after =
is optional). 这可能是您想要的(匹配=
和=
后的数字是可选的)。 As you are searching and replacing in a loop, compiling the regex separately will be more efficient than using re.sub
directly. 在循环搜索和替换时,单独编译regex比直接使用re.sub
更有效。
import re
pattern = re.compile(r'process\.control\.timeout(=\d+)?')
for line in process:
pattern.sub('process.control.timeout=900', line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.