![](/img/trans.png)
[英]match part of a string until it reaches the end of the line (python regex)
[英]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
函数,因为匹配尝试从头开始匹配字符串。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.