Python正则表达式在文件的行首搜索字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16862174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python regex search for string at beginning of line in file
提问by Glitch Cowboy
Here's my code:
这是我的代码:
#!/usr/bin/python
import io
import re
f = open('/etc/ssh/sshd_config','r')
strings = re.search(r'.*IgnoreR.*', f.read())
print(strings)
That returns data, but I need specific regex matching: e.g.:
这会返回数据,但我需要特定的正则表达式匹配:例如:
^\s*[^#]*IgnoreRhosts\s+yes
If I change my code to simply:
如果我将代码更改为简单:
strings = re.search(r'^IgnoreR.*', f.read())
or even
甚至
strings = re.search(r'^.*IgnoreR.*', f.read())
I don't get anything back. I need to be able to use real regex's like in perl
我什么也得不到。我需要能够在 perl 中使用真正的正则表达式
采纳答案by Casimir et Hippolyte
You can use the multiline mode then ^ match the beginning of a line:
您可以使用多行模式然后 ^ 匹配一行的开头:
#!/usr/bin/python
import io
import re
f = open('/etc/ssh/sshd_config','r')
strings = re.search(r"^\s*[^#]*IgnoreRhosts\s+yes", f.read(), flags=re.MULTILINE)
print(strings.group(0))
Note that without this mode you can always replace ^by \n
请注意,如果没有此模式,您始终可以替换^为\n
Note too that this file is calibrated as a tomato thus:
还要注意,这个文件被校准为番茄,因此:
^IgnoreRhosts\s+yes
is good enough for checking the parameter
足以检查参数
EDIT: a better way
编辑:更好的方法
with open('/etc/ssh/sshd_config') as f:
for line in f:
if line.startswith('IgnoreRhosts yes'):
print(line)
One more time there is no reason to have leading spaces. However if you want to be sure you can always use lstrip().
再一次没有理由有前导空格。但是,如果您想确保始终可以使用lstrip().

