實驗一
如下,對一個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]
這裏要注意的是在【】中‘.’不需要轉義符,但是在【】外需要轉義符。
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)