加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 特殊构造用法

发布时间:2020-12-14 06:47:23 所属栏目:百科 来源:网络整理
导读:问题: 查找不能有字符串abc的匹配 正则表达式 字符串 结果 r'a(?=bbb)' abbb a r'abbb' abbb abbb python 2.7 文档说明 https://docs.python.org/2/library/re.html (?=...) Matches if ... matches next, but doesn’t consume any of the string . This i

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

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

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) # 整个匹配规则替换
# 结果
accc

s = re.sub(r'a(?=bbb)',tmp) # (?=)里面的内容只做判断作用,不作为匹配结果,所以需要匹配某个规则,又不需要整个规则替换,可以用这个模式
# 结果
acccbbb

s = re.sub(r'a(?=bbb)','acccg<1>',tmp)
# 报错:invalid group reference 不是匹配结果,所以不能引用

s = re.sub(r'a(bbb)',tmp)
# 正常可以引用 
# 结果
acccbbb

s = 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)','xxg<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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读