这是我的代码:
#!/usr/bin/python
import io
import re
f = open('/etc/ssh/sshd_config','r')
strings = re.search(r'.*IgnoreR.*', f.read())
print(strings)
返回数据,但我需要特定的正则表达式匹配:例如:
^\s*[^#]*IgnoreRhosts\s+yes
如果我将代码简单地更改为:
strings = re.search(r'^IgnoreR.*', f.read())
甚至
strings = re.search(r'^.*IgnoreR.*', f.read())
我没有得到任何返回。我需要能够在 perl 中使用真正的正则表达式
最佳答案
您可以使用多行模式,然后 ^ 匹配一行的开头:
#!/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))
请注意,如果没有此模式,您始终可以将 ^
替换为 \n
另请注意,此文件被校准为番茄:
^IgnoreRhosts\s+yes
足以检查参数
编辑:更好的方法
with open('/etc/ssh/sshd_config') as f:
for line in f:
if line.startswith('IgnoreRhosts yes'):
print(line)
再一次没有理由有前导空格。但是,如果您想确保始终可以使用 lstrip()
。
关于Python 正则表达式在文件行首搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16862174/