【发布时间】:2018-12-07 15:11:26
【问题描述】:
我目前正在尝试匹配 eeprom 转储文本文件的模式以找到某个地址,然后在搜索中遇到时遍历 4 个步骤。我尝试了以下代码来查找模式
regexp_list = ('A1 B2')
line = open("dump.txt", 'r').read()
pattern = re.compile(regexp_list)
matches = re.findall(pattern,line)
for match in matches:
print(match)
这会扫描转储中的A1 B2 并在找到时显示。我需要在搜索条件中添加更多这样的地址,例如:'C1 B2', 'D1 F1'。
我尝试将regexp_list 设为列表而不是元组,但没有成功。
这是问题之一。接下来当我遇到搜索时,我想遍历 4 个地方,然后从那里读取地址(见下文)。
输入:
0120 86 1B 00 A1 B2 FF 15 A0 05 C2 D1 E4 00 25 04 00
在这里,当搜索找到A1 B2 模式时,我想移动 4 个位置,即从转储中保存来自 C2 D1 E4 的数据。
预期输出:
C2 D1 E4
我希望解释清楚。
#感谢@kcorlidy
这是我为删除第一列中的地址而必须输入的最后一段代码。
newtxt = (text.split("A0 05")[1].split()[4:][:5])
for i in newtxt:
if len(i) > 2:
newtxt.remove(i)
所以完整的代码看起来像
import re
text = open('dump.txt').read()
regex = r"(A1\s+B2)(\s+\w+){4}((\s+\w{2}(\s\w{4})?){3})"
for ele in re.findall(regex,text,re.MULTILINE):
print(" ".join([ok for ok in ele[2].split() if len(ok) == 2]))
print(text.split("A1 B2")[1].split()[4:][:5])
#selects the next 5 elements in the array including the address in 1st col
newtxt = (text.split("A1 B2")[1].split()[4:][:5])
for i in newtxt:
if len(i) > 2:
newtxt.remove(i)
输入:
0120 86 1B 00 00 C1 FF 15 00 00 A1 B2 00 00 00 00 C2
0130 D1 E4 00 00 FF 04 01 54 00 EB 00 54 89 B8 00 00
输出:
C2 0130 D1 E4 00
C2 D1 E4 00
【问题讨论】:
-
检查regexr.com/44htl并使用最后3组获取C2 D1 E4。
标签: python regex python-3.x pattern-matching eeprom