简体   繁体   English

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

[英]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. 您需要使用re.search函数,因为匹配尝试从头开始匹配字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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