![](/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.