Moshe
Moshe

Reputation: 5139

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?

Upvotes: 0

Views: 60

Answers (2)

mij
mij

Reputation: 532

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

Upvotes: 2

aghast
aghast

Reputation: 15310

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

Upvotes: 2

Related Questions