您的位置:首页 > 编程语言 > Python开发

在Python中使用正则表达式同时匹配邮箱和电话并进行简单的分类

2013-09-04 19:09 771 查看
在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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐