Python正则表达式不匹配。我受不了我

2024-04-25 17:29:26 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么这场比赛不成功?问题出在D上

import re

A = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
B = [0xa8, 0x2c, 0x53, 0x20, 0xca, 0x62, 0x49, 0x13]
C = [0x1A, 0xC4, 0x17, 0x05, 0x47, 0xE8, 0xA3, 0x83]
D = [0x81, 0x63, 0x1f, 0x55, 0xdb, 0x18, 0x2a, 0xab]


for bin_header in [A, B, C, D]:
    bin_str = ''.join(map(chr, bin_header))
    r = re.match(bin_str, bin_str)
    if not r:
        print map(hex, bin_header) # Surprise it prints D

Tags: inimportremapforifbinmatch
1条回答
网友
1楼 · 发布于 2024-04-25 17:29:26

您试图将字符串与正则表达式匹配,但忽略正则表达式语法。你的问题是:

>>> chr(0x2a)
'*'

*在正则表达式语法中有特殊的含义。"abc*"正则表达式将不匹配"abc*"字符串(例如,它将匹配"abcccc")。你知道吗

我建议你用=x in y而不是re.match来做这个。如果您不知道随机字节都是有效字符,甚至不知道字符是什么,那么将随机字节传递给正则表达式并不是一个好主意。你知道吗

下面是一个使用in的示例:

import re

A = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
B = [0xa8, 0x2c, 0x53, 0x20, 0xca, 0x62, 0x49, 0x13]
C = [0x1A, 0xC4, 0x17, 0x05, 0x47, 0xE8, 0xA3, 0x83]
D = [0x81, 0x63, 0x1f, 0x55, 0xdb, 0x18, 0x2a, 0xab]


for bin_header in [A, B, C, D]:
    bin_str = ''.join(map(chr, bin_header))
    matches =  bin_str in bin_str
    if not matches:
        print map(hex, bin_header) # Matches all examples.

即便如此,从未知字节流构造字符串也不能很好地处理字符编码,您应该使用正确的方法处理字节序列。你知道吗

如果您真的想使用字符串,可以将它们表示为十六进制字符串。因为十六进制字符串只是0-9a-z,所以您可以安全地使用任何字符串或正则表达式匹配等

for bin_header in [A, B, C, D]:
    bin_str = ''.join('%02x' % i for i in bin_header)
    matches =  bin_str in bin_str
    print(bin_str, matches)
    if not matches:
        print map(hex, bin_header)

给予

('ffffffffffffffff', True)
('a82c5320ca624913', True)
('1ac4170547e8a383', True)
('81631f55db182aab', True)

相关问题 更多 >

    热门问题