我有下面的路由器输出存储在一个文件中
-#- --length-- -----date/time------ path
3 97103164 Feb 7 2016 01:36:16 +05:30 taas/NN41_R11_Golden_Image
4 1896 Sep 27 2019 14:22:08 +05:30 taas/NN41_R11_Golden_Config
5 1876 Nov 27 2017 20:07:50 +05:30 taas/nfast_default.cfg
我想从文件中搜索子字符串'Golden_Image'
,并获取完整路径。所以这里,需要的输出是这个字符串:
taas/NN41_R11_Golden_Image
第一次尝试:
import re
with open("outlog.out") as f:
for line in f:
if "Golden_Image" in line:
print(line)
输出:
3 97103164 Feb 7 2016 01:36:16 +05:30 taas/NN41_R11_Golden_Image
第二次尝试
import re
hand = open('outlog.out')
for line in hand:
line = line.rstrip()
x = re.findall('.*?Golden_Image.*?',line)
if len(x) > 0:
print x
输出:
['3 97103164 Feb 7 2016 01:36:16 +05:30 taas/NN41_R11_Golden_Image']
这些都不能提供所需的输出。我怎样才能解决这个问题?你知道吗
如果路径可以包含空格,那么这实际上是一个令人惊讶的复杂过程。
您需要使用maxsplit参数来
split
标识路径字段。你知道吗一次阅读全部内容,然后再进行搜索是没有效率的。相反,可以逐行读取文件,如果行符合条件,则可以提取路径,而无需进一步拆分和使用RegEx。你知道吗
使用以下正则表达式获取路径
链接:https://regex101.com/r/zuH0Zv/1
如果工作代码为:
在线上进行拆分,并检查拆分部分中是否存在“Golden\u Image”字符串。你知道吗
或者
示例:
相关问题 更多 >
编程相关推荐