我有这种长日志文件
2012-02-03 18:35:34 SampleClass6 [INFO] everything normal for id 174025851
2012-02-03 18:35:34 SampleClass4 [FATAL] system problem at id 1991740254
2012-02-03 18:35:34 SampleClass3 [DEBUG] detail for id 1304807656
2012-02-03 18:35:34 SampleClass3 [WARN] missing id 1740
我想准确地找到id=1740
,并打印行,但id=174025851
也在其中。如何在一行和打印行中准确地找到字符串id=1740
for line in f:
if str(id) in line:
print(line)
它还打印第一行和第二行,但我只想第四行,id为1740
冒着为一个已经有很多答案的问题添加另一个答案的风险,下面是我认为正则表达式解析器在这里的最佳使用方式:
这使得:
您在这里所做的是使用解析器查找以以下内容结尾的行:“id”,后跟空格,后跟一个或多个数字(您在一个组中捕获),可以选择后跟任意数量的空格
然后将捕获的组转换为int并与id进行比较
顺便说一句,id存储在名为
the_id
的变量中,因为id
是内置函数的名称,因此不是一个好的变量名称选择(干扰内置函数的使用)更新
<> P.Askter现在已经澄清,ID可以出现在直线的中间,不一定在末端。p>这可以通过对正则表达式进行简单的调整来轻松处理。将上述代码中的相关行更改为:
现在删除对数字之后应该出现的内容的任何检查
因为表示“一个或多个”的
+
也是贪心的(也就是说,它尽可能多地匹配与其相关的模式的部分),ID的整体由括号中的组匹配,而不需要指定它后面的内容给定输入文件
现在将输出:
您可以使用正则表达式
您可以使用regex,比如id后跟空格。 或者如果id始终位于行的末尾。然后使用 如果line.endswith('id'+id)为true,则执行逻辑
相关问题 更多 >
编程相关推荐