正则表达式 特殊构造用法

来源:互联网 发布:海康威视监控软件 编辑:程序博客网 时间:2024/06/11 10:08

问题: 查找不能有字符串abc的匹配

正则表达式字符串结果r'a(?=bbb)'abbbar'abbb'abbbabbb

python 2.7 文档说明 https://docs.python.org/2/library/re.html

(?=...)
Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion . For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.
(?!...)
Matches if ... doesn’t match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if it’s not followed by 'Asimov'.

(?=) 可以看出这种形式的作用是判断条件不计入匹配结果,仅仅是判断条件

(?<=...) Group references are not supported even if they match strings of some fixed length. Note that patterns which start with positive lookbehind assertions will not match at the beginning of the string being searched;

说明(?) 里匹配到的内容都不能使用组引用比如\1 \g<1>引用对应的内容

同理re.sub, re.search的替换也同样适合这种原理

tmp = 'abbb's = re.sub(r'a(bbb)', 'accc', tmp) # 整个匹配规则替换# 结果acccs = re.sub(r'a(?=bbb)', 'accc', tmp) # (?=)里面的内容只做判断作用,不作为匹配结果,所以需要匹配某个规则,又不需要整个规则替换,可以用这个模式# 结果acccbbbs = re.sub(r'a(?=bbb)', 'accc\g<1>', tmp)# 报错:invalid group reference 不是匹配结果,所以不能引用s = re.sub(r'a(bbb)', 'accc\g<1>', tmp)# 正常可以引用 # 结果acccbbbs = re.findall(r'a(?=bbb)', 'abbb')# 结果  不是匹配结果,所以不能引用 ['a']

继续深入(?=)用法

re.findall('a(?=bhc)d', 'abhcd')
所以这个表达式的意思是:
a后边的表达式必须是bhc, 后面是d
结果: []

为什么? 因为这个(?=bhc)只是针对a后面的匹配, 不是针对d前面的,而对d来说,前面其实是没有匹配表达式
SO, d前面必须是a, 而a后面又必须时bhc,所以永远匹配不到任何东西
应该改成这样:
re.findall('a(?=bhc)\w*d', 'abhcd')
结果: ['abhcd']

分组引用问题

s = re.sub(r'a(?P<hello>xyz)', 'xx\g<hello>', 'axyz') # 使用组名引用 s = re.sub(r'a(xyz)', 'hello \g<1>', 'axyz')  # 使用序号引用s = re.sub(r'a(xyz)', 'hello \1', 'axyz')  # 乱码

使用组名或者序号\g<1>来引用是没问题的,但是\1 \2引用会出问题 , 查了下资料,直接用\1这种引用的话,如果后面也是数字比如\10就会引用到第10组,所以避免歧义,还是用\g<1>这种吧

相关链接 http://www.cnblogs.com/wangqiguo/archive/2012/05/08/2486548.html