负向展望python正则表达式 [英] Negative look ahead python regex

查看:61
本文介绍了负向展望python正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当字符串'02 d0'没有出现在字符串的特定位置时,我想正则表达式匹配字节序列.不能出现此两个字节的字符串的位置是字节位置6和7,从右侧的第0个字节开始.

I would like to regex match a sequence of bytes when the string '02 d0' does not occur at a specific position in the string. The position where this string of two bytes cannot occur are byte positions 6 and 7 starting with the 0th byte on the right hand side.

这就是我一直在测试的东西:

This is what I have been using for testing:

#!/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",我该怎么做?

I looked at this example, but that method is less restrictive than I need. Could someone explain why I can only match properly when the negative look ahead is at the end of the string? What do I need to do to match when '02 d0' does not occur in this specific bit position?

推荐答案

先行符是零宽度",表示它们不占用任何字符.例如,这两个表达式将永远不匹配:

Lookaheads are "zero-width", meaning they do not consume any characters. For example, these two expressions will never match:

  1. (?=foo)bar
  2. (?!foo)foo
  1. (?=foo)bar
  2. (?!foo)foo

要确保数字不是某个特定数字,可以使用:

To make sure a number is not some specific number, you could use:

(?!42)\d\d # will match two digits that are not 42

在您的情况下,可能看起来像这样:

In your case it could look like:

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

或:

(?!02 d0)[\da-f]{2} [\da-f]{2}

这篇关于负向展望python正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆