day 18 作业 正则表达式

# 1.写一个验证是否是手机号码的正则 号段有:# 中国移动号段有:134、147、150、178、182、198# 135、 151、 183、# 136、 152、 184、# 137、 157、 187、# 138、 158、 188、# 139、 159、# 中国联通号段有:130、155、145、176、185、166# 131 156 186# 132# 中国电信号段有:133、149、153、173、180、199# 177 181# 189

 1 import re
 2 def num(x):
 3     num = x
 4     c = r"^13[4,5,6,7,8,9]\d{8}|" \
 5         r"^147\d{8}|" \
 6         r"^15[0,1,2,7,8,9]\d{8}|" \
 7         r"^178\d{8}|" \
 8         r"^18[2,3,4,7,8]\d{8}|" \
 9         r"^198\d{8}"
10     c1 = r"^13[0,1,2]\d{8}|" \
11          r"^145\d{8}|" \
12          r"^15[5,6]\d{8}|" \
13          r"^176\d{8}|" \
14          r"^18[5,6]\d{8}|" \
15          r"^166\d{8}"
16     c2 = r"^133\d{8}|" \
17          r"^149\d{8}|" \
18          r"^153\d{8}|" \
19          r"^17[3,7]\d{8}|" \
20          r"^18[0,1,9]\d{8}|" \
21          r"^199\d{8}"
22     a = re.findall(c, num)
23     a1 = re.findall(c1, num)
24     a2 = re.findall(c2, num)
25     if num in a:
26         print("你输入的手机号为中国移动号码:%s" % (num))
27     elif num in a1:
28         print("你输入的手机号为中国联通号码:%s" % (num))
29     elif num in a2:
30         print("你输入的手机号为中国电信号码:%s" % (num))
31     elif x == "end":
32         return "end"
33     else:
34         print("输入有误")
35 while True:
36     if num(input("请输入")) == "end":
37         break

# 2.写一个验证是否是邮箱的正则
# 规则要求如下:
# 1.开头可以是字母、数字
# 2.有6位构成
# 3.接着是 @ 符号
# 4.邮箱可以是:163 qq sina 126
# 5.接着是:.符号
# 6. 最后是:com
# 比如:下面就是符合条件的字符串:
# 123456 @ 163.com
# abcdef @ qq.com
# 可以自查一下正则的分组

 1 def text(x):
 2     a = re.compile(r"^[a-zA-Z0-9]{6}@(163|qq|sina|126)\.com$")
 3     b = a.match(x)
 4     if x == "end":
 5         return "end"
 6     elif b == None:
 7         print("错误")
 8     else:
 9        a1 = re.match(r"^[a-zA-Z0-9]{6}@(163|qq|sina|126)\.com$",x)
10        print(a1.group())
11 while True:
12     if text(input("邮箱地址")) == "end":
13         break

猜你喜欢

转载自www.cnblogs.com/liyaobin/p/10012759.html