繁体   English   中英

Python正则表达式库即使匹配也无法匹配

[英]Python regex library can't match even though it should

我的剧本:

#!/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='))

假定遍历给定文件中的各行并匹配提供的regex(如果存在),追加到res并最终返回res

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

SocketAcceptPort=8003

仍然打印[]

怎么会?

检查文档是否存在re.match ,这是我们的第一句话:

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

注意“字符串开始”部分吗? 您需要使用其他功能来匹配行中的任何地方。 例如,以下文档中的match为:

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

如果要查找端口列表,则可以不使用字符串比较:

#!/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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM