简体   繁体   中英

Python regex: How to match a string at the end of a line in a file?

I need to match a string at the end of a line of a file.

The contents of the file are:

   network1:
     type: Internal

I have made this regex to get the first line but it does not match anything. Note that my code's requirement is that the string which is to be matched is stored in a variable. Therefore:

var1 = 'network1'
re.match('\s+%s:'%var1,line)

However, when I check this regex on the interpreter, it works.

>> import re 
>> line = '  network1:'
>> var1 = 'network1'
>> pat1 =  re.match('\s+%s:'%var1,line)
>> var2 = pat1.group(0)
>> print var2
     '  network1:'

You need to use re.search function, since match tries to match the string from the beginning.

var1 = 'network1'
print(re.search(r'.*(\s+'+ var1 + r':)', line).group(1))

Example:

>>> import re
>>> s = 'foo network1: network1:'
>>> var1 = 'network1'
>>> print(re.search(r'.*(\s+'+ var1 + r':)', s).group(1))
 network1:
>>> print(re.search(r'.*(..\s+'+ var1 + r':)', s).group(1)) # to check whether it fetches the last string or not.
1: network1:

So, you should do like

with open(file) as f:
    for line in f:
        if var1 in line:
            print(re.search(r'.*(\s+'+ var1 + r':)', s).group(1))

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