在Python中匹配模式
我有一个目录叫做“/pcap_test”,里面有几个日志文件。每个文件的内容大概是这样的:
数据包: 1 (358 字节), 生命周期: 1, 应用: itunes (进入), 状态: 已终止, 堆栈: /ETH/IP/UDP/itunes, 错误: 无
数据包: 2 (69 字节), 生命周期: 2, 应用: zynga (进入), 状态: 正在检查, 堆栈: /ETH/IP/UDP, 错误: 无
数据包: 3 (149 字节), 生命周期: 2, 应用: pizzeria (进入), 状态: 已终止, 堆栈: /ETH/IP/UDP/pizzeria, 错误: 无
在这种情况下,我想要的输出是第二行,因为“应用”中的内容在“堆栈:”中并不存在。
我写了一个小的 Python 脚本,循环遍历这个目录,打开每个文件并打印输出:
import os
list = os.listdir("/home/test/Downloads/pcap_test")
print list
for infile in list:
infile = os.path.join("/home/test/Downloads/pcap_test" , infile)
if os.path.isfile(infile):
str = file(infile, 'r').read()
print str
我用 grep 命令得到了输出,但在 Python 脚本中无法使用同样的方法。大概是这样的:
grep -vP 'App: ([^, ]*) \(INTO\).*Stack: .*\1.*$' xyz.pcap.log | grep -P 'App: ([^, ]*) \(INTO\)'
因为我已经有一个名为“str”的文件,我想用这个文件,而不是单独的日志文件,来获取输出。
在这方面的任何帮助都将非常感谢。
1 个回答
0
首先,我建议不要使用像 str
这样的变量名,因为这是Python用来表示字符串这种基本数据类型的名字。
因为grep是一个命令行的正则表达式工具,而你已经有了一个可以用的正则表达式,所以你只需要学习如何使用Python的 re
模块。
有一点比较难的是如何实现grep的 -v
功能。我建议你逐行读取文件,只有当某一行不符合你的第一个正则表达式,但符合第二个正则表达式时才打印这一行,像这样:
if os.path.isfile(infile):
with file(infile, 'r') as logFile: #this will close the file pointer automatically when you finish
for line in logFile: #read logFile one line at a time
firstReMatch = re.match(r'App: ([^, ]*) \(INTO\).*Stack: .*\1.*$', line) #check if this line matches your first regex
secondReMatch = re.match(r'App: ([^, ]*) \(INTO\)', line) #check if this line matched your second regex
if secondReMatch and not firstReMatch: #"not" to capture the inverse match
print line #print the line.
根据你的数据,你可能想要 使用 re.search()
而不是 re.match()