Gli*_*boy 13 python regex file-io
这是我的代码:
#!/usr/bin/python
import io
import re
f = open('/etc/ssh/sshd_config','r')
strings = re.search(r'.*IgnoreR.*', f.read())
print(strings)
Run Code Online (Sandbox Code Playgroud)
返回数据,但我需要特定的正则表达式匹配:例如:
^\s*[^#]*IgnoreRhosts\s+yes
Run Code Online (Sandbox Code Playgroud)
如果我将代码更改为:
strings = re.search(r'^IgnoreR.*', f.read())
Run Code Online (Sandbox Code Playgroud)
甚至
strings = re.search(r'^.*IgnoreR.*', f.read())
Run Code Online (Sandbox Code Playgroud)
我什么都没收到.我需要能够在perl中使用真正的正则表达式
Cas*_*yte 18
您可以使用多线模式,然后^匹配一行的开头:
#!/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))
Run Code Online (Sandbox Code Playgroud)
请注意,如果没有这个模式,你可以随时更换^
的\n
另请注意,此文件已校准为番茄,因此:
^IgnoreRhosts\s+yes
Run Code Online (Sandbox Code Playgroud)
足以检查参数
编辑:一个更好的方法
with open('/etc/ssh/sshd_config') as f:
for line in f:
if line.startswith('IgnoreRhosts yes'):
print(line)
Run Code Online (Sandbox Code Playgroud)
再一次,没有理由拥有领先的空间.但是,如果您想确保可以随时使用lstrip()
.