在Python使用正則表達式需要使用re(regular exprssion)模塊,使用正則表達式的難點就在于如何寫好p=re.compile(r' 正則表達式')的內容。
下面是在Python中使用正則表達式同時匹配郵箱和電話并進行簡單的分類的代碼,本文只進行了簡單的分類,讀者可使用補充部分提供的信息進行詳細分類。
import re
p=re.compile(r'^[\w\d]+[\d\w\_\.]+@([\d\w]+)\.([\d\w]+)(?:\.[\d\w]+)?$|^(?:\+86)?(\d{3})\d{8}$|^(?:\+86)?(0\d{2,3})\d{7,8}$')
def mail_or_phone(p,s):
m=p.match(s)
if m==None:
print 'mail address or phone number is wrong'
else:
if m.group(1)!=None:
if m.group(1)=='vip':
print 'It is %s mail,the address is %s' %(m.group(2),m.group())
else:
print 'It is %s mail,the address is %s' %(m.group(1),m.group())
else:
if m.group(3)!=None:
print 'It is mobilephone number,the number is %s' %m.group()
else:
print 'It is telephone number,the number is %s' %m.group()
if __name__=='__main__':
s=[]
s.append('tju_123@163.com')
s.append('123@tju.edu.cn')
s.append('123456@vip.qq.com')
s.append('+8615822123456')
s.append('0228612345')
for i in range(len(s)):
mail_or_phone(p,s[i])
結果如下:
It is 163 mail,the address is tju_123@163.com
It is tju mail,the address is 123@tju.edu.cn
It is qq mail,the address is 123456@vip.qq.com
It is mobilephone number,the number is +8615822123456
It is telephone number,the number is 0228612345
該代碼中正則表達式分為三部分:
(1) ^[\w\d]+[\d\w\_\.]+@([\d\w]+)\.([\d\w]+)(?:\.[\d\w]+)?$ 這部分用于匹配郵箱
(2) ^(?:\+86)?(\d{3})\d{8}$?這部分用于匹配移動電話
(2)?^(?:\+86)?(0\d{2,3})\d{7,8}$?這部分用于匹配固定電話
郵箱中@后面有的有一個‘.',有的有兩個‘.’,而且有的@后面緊挨著的是‘vip’,而不是‘qq’等郵箱標識
移動電話和固定電話在來電顯示中經常出現‘+86’,所以匹配過程中要注意這一點
正則表達式中使用了()進行分組,然后可以通過group(i)來獲得相應分組的信息來進行判斷
補充:
1.常用的郵箱:
QQ: @qq.com或者@foxmail.com
網易: @163.com、@126.com、@yeah.net
google: @gmail.com
新浪: @sina.com、@sina.cn
搜狐: @sohu.com
高校: @tju.edu.cn等
2.中國三大運營商手機號段
移動:134、135、136、137、138、139、147、150、152、154、157、158、159、182、183、187、188
聯通:130、131、132、155、156、185、186
電信:133、153、180、189