Python 正则表达式:如何匹配文件中一行末尾的字符串?

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

我需要匹配文件行末尾的字符串。

文件内容为:

   network1:
     type: Internal

我已将此正则表达式设为第一行,但它不匹配任何内容。请注意,我的代码要求是要匹配的字符串存储在一个变量中。因此:

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

然而,当我在解释器上检查这个正则表达式时,它起作用了。

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

您需要使用 re.search 函数,因为 match 会尝试从头开始匹配字符串。

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

示例:

>>> 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:

所以,你应该这样做

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