RegEx以在3个字符的子字符串中查找唯一字符的所有索引

问题描述 投票:0回答:1

我正在使用finditer获得两个字节的模式的索引。

my_val = [0, 1]
[(m.start(0), m.end(0)) for m in re.finditer(myval, content)]

但是现在我还需要唯一的值/位置,其中前两个字节与my_val相同,但是第三个值是唯一的。即以013 234 523 015 68 012 9 015 014 012 013 013 012 012这样的模式,我需要013015012014忽略重复的值。

regex python-3.x
1个回答
0
投票

首先,模式应该是一个字节,请注意一个列表。

然后,您可以使用字典存储已找到的匹配项:

content = '0120150160150132468451018'
content = bytes(map(int, content))
my_val = b'\x00\x01.'
d = dict()
for m in re.finditer(my_val, content):
    k = m.group(0)
    if k not in d :
        d[m.group(0)] = (m.start(0), m.end(0))
res = d.values()

注意:将bytes强制转换为listint,将listint强制转换为bytes:]]

>>> list(b'\x00\x03\xa2')
[0, 3, 162]

>>> bytes([0, 3, 162])
b'\x00\x03\xa2'
© www.soinside.com 2019 - 2024. All rights reserved.