user5826447 user5826447 - 29 days ago 6
Python Question

Python variable in re.match

I am trying to write a function that takes in a key (among other things) and returns the word after this key in the file. The code below works, but only if the key happens to be the first phrase in the file. Could anyone point out where I'm going wrong?

def findmatch(key, split_by, tempsl, filename, temp):
rx=r''+key+'(.*)'
f = open(tempsl + filename, 'r', encoding='windows-1252')
for eachline in f:
string=re.match(rx, eachline)
if string:
return (string.group().split(' ')[split_by])
else:
return "didn't work"

Answer

You end your for loop after the first iteration because

if string:
    return (string.group().split(' ')[split_by])
else:
    return "didn't work"

will always break the loop. It will return some result only if you have a keyword in first line. So I suggest this:

for eachline in f:
    string=re.match(rx, eachline)
    if string:
        return (string.group().split(' ')[split_by])
else: # else statemant is a part of for loop (moved to the left)
    return "didn't work" 

and try this:

m = re.search('(?<=' + key + ')\w+', eachline)
m.group(0)