搜索包含一些文本的行,替换完整行 python
所以我试图搜索某个字符串,例如可能是: 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 还很陌生。
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. 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. I have a feeling I will need to use regex with a wildcard? But I'm pretty new to python.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有正则表达式:
或者
如果您要匹配的文本位于行的开头,请使用
line.startswith("process.control.timeout")
而不是"process.control.timeout “在行
。Without regex:
or
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
.你是对的,正则表达式是正确的选择。
You are correct, regex is the way to go.
这可能就是您想要的(匹配
=
和=
后面的数字是可选的)。当您在循环中搜索和替换时,单独编译正则表达式比直接使用re.sub
更有效。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 usingre.sub
directly.