Python正则表达式不匹配。我受不了
为什么这场比赛不成功?问题在于DPython正则表达式不匹配。我受不了,python,regex,Python,Regex,为什么这场比赛不成功?问题在于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_
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
您试图将字符串与正则表达式匹配,但忽略正则表达式语法。这是你的问题:
>>> chr(0x2a)
'*'
*
在正则表达式语法中具有特殊意义“abc*”
正则表达式将与字符串不匹配(例如,它将匹配“abcccc”
)
我建议您使用=
或y中的x
而不是re.match
。如果您不知道随机字节都是有效字符,甚至不知道字符是什么,那么将随机字节传递给正则表达式不是一个好主意
下面是一个在中使用的示例:
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)
给予
你的正则表达式在哪里?你为什么要用正则表达式?!Saleem:re.match(bin_str,bin_str)0x2a
是一个星号“*”
。星号与正则表达式中的普通字符不匹配。模式'\x81c\x1fU\xdb\x18*\xab'
自身不匹配。Biffen:没关系,我需要解决这个问题。我正在匹配二进制字符串。
('ffffffffffffffff', True)
('a82c5320ca624913', True)
('1ac4170547e8a383', True)
('81631f55db182aab', True)