简体   繁体   English

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

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

My script: 我的剧本:

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

Supposed to loop through the lines in the file given and match the regex provided, if exists, append to res and eventually return res . 假定遍历给定文件中的各行并匹配提供的regex(如果存在),追加到res并最终返回res

The content of /opt/conf/streaming.cfg contains a line: /opt/conf/streaming.cfg的内容包含一行:

SocketAcceptPort=8003

Still prints [] 仍然打印[]

How come? 怎么会?

Checking the docs for re.match gives us this first sentence: 检查文档是否存在re.match ,这是我们的第一句话:

If zero or more characters at the beginning of string match 如果在字符串开头匹配零个或多个字符

Notice the part about "beginning of string"? 注意“字符串开始”部分吗? You need to use a different re function to match anywhere in the line. 您需要使用其他功能来匹配行中的任何地方。 For example, further down in the docs for match is this note: 例如,以下文档中的match为:

If you want to locate a match anywhere in string, use search() instead 如果要在字符串中的任意位置找到匹配项,请使用search()代替

If you're looking for a list of ports, could you not use a string comparison instead: 如果要查找端口列表,则可以不使用字符串比较:

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

giving the result: 给出结果:

['SocketAcceptPort=8003']

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

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