Python 正则表达式在文件行首搜索字符串

标签 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)

返回数据,但我需要特定的正则表达式匹配:例如:

^\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/

相关文章:

python - 在 Google Cloud Datastore 与 Google Cloud Bigtable 中存储用户事件历史记录

python - 在 csv.reader 中获取原始行?

python - 如何在计算多个特定字符串的出现次数后添加字符串

javascript - 如何使以下正则表达式匹配并替换未闭合的双引号?

c# - 如何读取日志文件的最后 "n"行

Python以utf-8编码逐行读取大文件

python - 在 PyObjc 和 Cocoa 中实现 NSText 委托(delegate)方法

python - 改进 Python 中的模糊匹配算法

c# - 如何在进行正则表达式搜索时排除组合?

java - 在 Android 中逐字读取文件的最佳方法是什么