负前瞻python正则表达式

负前瞻python正则表达式,python,regex,negative-lookahead,Python,Regex,Negative Lookahead,当字符串“02 d0”未出现在字符串中的特定位置时,我希望正则表达式匹配字节序列。这两个字节的字符串不能出现的位置是从右侧第0个字节开始的字节位置6和7 这就是我一直在测试的内容: #!/usr/bin/python import re p0 = re.compile('^24 [\da-f]{2} 03 (01|03) [\da-f]{2} [\da-f]{2} [\da-f]{2} (([^0])| (0[^2])|(02 [^d])|(02 d[^0])) 01 c2 [\da-f

当字符串“02 d0”未出现在字符串中的特定位置时,我希望正则表达式匹配字节序列。这两个字节的字符串不能出现的位置是从右侧第0个字节开始的字节位置6和7

这就是我一直在测试的内容:

#!/usr/bin/python
import re

p0 = re.compile('^24 [\da-f]{2} 03 (01|03) [\da-f]{2} [\da-f]{2} [\da-f]{2} (([^0])|    (0[^2])|(02 [^d])|(02 d[^0])) 01 c2 [\da-f]{2} [\da-f]{2} [\da-f]{2} 23')
p1 = re.compile('^24 [\da-f]{2} 03 (01|03) [\da-f]{2} [\da-f]{2} [\da-f]{2} (([^0])|(0[^2])|(02 [^d])|(02 d[^0])) 01')
p2 = re.compile('^24 [\da-f]{2} 03 (01|03) [\da-f]{2} [\da-f]{2} [\da-f]{2} (([^0])|(0[^2])|(02 [^d])|(02 d[^0]))')
p3 = re.compile('^24 [\da-f]{2} 03 (01|03) [\da-f]{2} [\da-f]{2} [\da-f]{2} (?!02 d0) 01')
p4 = re.compile('^24 [\da-f]{2} 03 (01|03) [\da-f]{2} [\da-f]{2} [\da-f]{2} (?!02 d0)')

yes = '24 0f 03 01 42 ff 00 04 a2 01 c2 00 c5 e5 23'
no  = '24 0f 03 01 42 ff 00 02 d0 01 c2 00 c5 e5 23'

print p0.match(yes)  # fail
print p0.match(no)   # fail
print '\n'
print p1.match(yes)  # fail
print p1.match(no)   # fail
print '\n'
print p2.match(yes)  # PASS
print p2.match(no)   # fail
print '\n'
print p3.match(yes)  # fail
print p3.match(no)   # fail
print '\n'
print p4.match(yes)  # PASS
print p4.match(no)   # fail
我看了,但这种方法没有我需要的那么严格。有人能解释一下为什么我只能在消极的前瞻性处于字符串末尾时才能正确匹配吗?当“02 d0”未出现在此特定位位置时,我需要做什么来匹配?

Lookaheads是“零宽度”,这意味着它们不使用任何字符。例如,这两个表达式永远不会匹配:

  • (?=foo)条
  • (?!foo)foo
  • 要确保某个数字不是某个特定的数字,您可以使用:

    (?!42)\d\d # will match two digits that are not 42
    
    在您的情况下,它可能看起来像:

    (?!02)[\da-f]{2} (?!0d)[\da-f]{2}
    
    或:


    我是唯一一个认为
    [0-9a-f]
    [\da-f]
    更可读的人吗?你的意思是“位置7和8”,对吗?为什么要使用[\da-f]。@umayneverknow
    [\da-f]
    匹配十六进制数字。等效地,可以使用
    [0-9a-f]
    (?!02 d0)[\da-f]{2} [\da-f]{2}