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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章