PYTHON正则 复杂表达式 括号 非贪心 踩坑小记

实验一
如下,对一个txt中的邮箱进行匹配。
首先是txt='[email protected]'

import re
import pprint
txt='Yang [email protected]'
a=re.compile(r'[\w\W.]+(@saicmotor\.com',re.I)
s=a.search(txt)
pprint.pprint(s)

s=Yang [email protected]
这里要注意的是在【】中‘.’不需要转义符,但是在【】外需要转义符。


实验二br/>当txt='[email protected]@saicmotor.com'时,重复上面的实验,会发现出现了贪心的问题,[email protected]@saicmotor.com。这不是我们想要的,因此需要限制贪心。
这里看上去是后缀出现了两次,但是如果对后缀经行非贪心竟然没有用~怎么办?
如下修改即可:

import re
import pprint
txt='[email protected]@saicmotor.com'
a=re.compile(r'([\w\W.]+?(@saicmotor\.com))',re.I)
s=a.search(txt)
pprint.pprint(s)

原因在于[\w\W.]+将第一个@saicmotor.com匹配进去了,这个问题困惑了我1个小时。


实验三
解决了贪心的问题,开始匹配多个人的邮箱。
txt='Yang [email protected] zhu [email protected]'

import re
import pprint
txt='[email protected]   [email protected]'
a=re.compile(r'[\w\W.]+?(@saicmotor\.com)',re.I)
s=a.findall(txt)
print(s)

得到的结果是['@saicmotor.com', '@saicmotor.com']
what?!
原因在于那个括号,去掉括号就可以,或者在整个正则表达式外面加括号,因为结果只反馈括号里的内容,当然加多个括号也是可以的。如下:

a=re.compile(r'([\w\W.]+?(@saicmotor\.com))',re.I)
a=re.compile(r'[\w\W.]+?@saicmotor\.com',re.I)

猜你喜欢

转载自blog.51cto.com/14156081/2347106