即使它应该

时间:2017-12-05 10:01:49

标签: python regex

我的剧本:

#!/usr/bin/env python
import os
import re

def grep(filepath, regex):
    regObj = re.compile(regex)
    res = []
    with open(filepath) as f:
        for line in f:
            if regObj.match(line):
                res.append(line)
    return res

print(grep('/opt/conf/streaming.cfg', 'Port='))

假设循环遍历给定文件中的行并匹配提供的正则表达式(如果存在),追加到res并最终返回res

/opt/conf/streaming.cfg的内容包含一行:

SocketAcceptPort=8003

仍打印[]

怎么回事?

2 个答案:

答案 0 :(得分:2)

检查re.match的文档会给我们第一句话:

  

如果字符串开头的零个或多个字符匹配

注意关于“字符串开头”的部分?您需要使用不同的re函数来匹配行中的任何位置。例如,match的文档中的更多内容是此注释:

  

如果要在字符串中的任何位置找到匹配项,请使用search()代替

答案 1 :(得分:2)

如果您正在寻找端口列表,请不要使用字符串比较:

#!/usr/bin/env python
import os
import re

def grep(filepath, substring):
    res = []
    with open(filepath) as f:
        for line in f:
            if substring in line:
                res.append(line.rsplit("\n")[0])
    return res


print(grep('/opt/conf/streaming.cfg', 'Port='))

给出结果:

['SocketAcceptPort=8003']
相关问题