简体   繁体   中英

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 .

The content of /opt/conf/streaming.cfg contains a line:

SocketAcceptPort=8003

Still prints []

How come?

Checking the docs for re.match gives us this first sentence:

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:

If you want to locate a match anywhere in string, use search() instead

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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