python - 使用 re.finditer(或其他函数)查找 str 并在 python 中解析出以下数据

标签 python regex

我正在尝试在 Python 3.4 中构建我的第一个程序,旨在从 Windows XP 中的 setupapi.dev.log 文件(一个基于文本的日志文件,以 ASCII 格式存储数据)中解析出有趣的取证数据。

我目前正在使用 re.finditer 来识别“VID”的位置,但需要指定它是我感兴趣的以下 5 个字符。

到目前为止,我的代码看起来像这样:

import sys 
import re

file_path = sys.argv[1]
file_pointer = open(file_path)
data = (file_pointer.read()

find_vid="VID"
v = re.finditer(find_vid, data)
for each in v:
  print('%02d-%02d: %s' % (each.start(), each.end(), each.group()))

结果:

188275-188278: VID
188785-188788: VID
...

有没有办法使用这个函数来解析文本文件中 VID 后面的文本?

最佳答案

为了获得模式后的 5 个字符,您可以将 re.findall 与组一起使用:

>>> s = '123VID foo 456VID bar '
>>> re.findall('VID(.{5})', s)
[' foo ', ' bar ']

来自 docs :

If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.

如果你想坚持使用 finditer,语法会稍微复杂一些,因为你必须手动提取组:

>>> [m.group(1) for m in re.finditer('VID(.{5})', s)]
[' foo ', ' bar ']

关于python - 使用 re.finditer(或其他函数)查找 str 并在 python 中解析出以下数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41979116/

相关文章:

c++ - 正则表达式替换捕获,然后进行数字分离

python - 将具有匹配索引的数组元素清零

python - PyCrypto 生成错误的签名

python - Telethon iter_messages 适用于一个 channel ,但不适用于另一个 channel

python - 如何使用计数器重新启动我的 while 循环

regex - 如何使用 perl regex 从 '[1]' 中提取数字值?

python - 读取具有不同数据类型的二进制文件

ruby - 缓慢的 Ruby 正则表达式通过奇怪的变化变得快速

python - 从 .CSV 获取主题标签并在 Python 3 中对它们进行计数

c++ - 用于选择每个空格的正则表达式