python正则表达式小练习

最近刚刚学了一点点python,自己就动手写了一个很简单很简单的正则表达式验证的小例子,代码如下:

 1 import re
2 while 1:
3 print '请输入验证:'
4 print '1.网址 2.IP地址 3.电子邮件 4.QQ号码 5.退出'
5 num=raw_input()
6 if num=='1':
7 yourweb=raw_input('请输入网址:\n')
8 website=re.compile(r'[a-zA-z]+://[^\s]*')
9 match=website.match(yourweb)
10 if match:
11 print match.group()
12 else:
13 print 'wrong website'
14 if num=='2':
15 youip=raw_input('请输入ip地址:\n')
16 ipaddress=re.compile(r'((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)')
17 match=ipaddress.match(youip)
18 if match:
19 print match.group()
20 else:
21 print 'wrong ipaddress'
22 if num=='3':
23 yourmail=raw_input('请输入电子邮件地址:\n')
24 email=re.compile(r'\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*')
25 match=email.match(yourmail)
26 if match:
27 print match.group()
28 else:
29 print 'wrong email address'
30 if num=='4':
31 yourqq=raw_input('请输入QQ:\n')
32 qqnum=re.compile(r'[1-9]\d{4,}')
33 match=qqnum.match(yourqq)
34 if match:
35 print match.group()
36 else:
37 print 'worng QQ num'
38 if num=='5':
39 break
40



原文地址:https://www.cnblogs.com/Lamboy/p/2310619.html