标题:正则表达式小训练
注:此代码注释符可随时删去
# encoding=utf-8
import re
# 1.匹配某个字符串
#text = "hello"
# match可将正则表达式按照规则进行匹配
#ret = re.match('he',text)
# group 可将匹配到的字符串打印出来
#print(ret.group())
# 2.点.匹配任意的字符
#text = "hello"
# . 只能匹配一个字符, . 不能匹配换行符
#ret = re.match('.',text)
#print(ret.group())
# 3. \d : 匹配任意的数字(0-9)
#text = "0"
#ret = re.match('\d',text)
#print(ret.group())
# 4. \D : 匹配任意的非数字
#text = "a"
#ret = re.match('\D',text)
#print(ret.group())
# 5.\s 匹配的是空白字符(\n \t \r 空格)
#text = " \n "
#ret = re.match('\s',text)
#print(ret.group())
# 6.\w匹配到的是 a-z 和 A-Z 以及数字和下划线
#text = "a"
#ret = re.match('\w',text)
#print(ret.group())
# 7.\W 与 \w 相反
#text = "+"
#ret = re.match('\W',text)
#print(ret.group())
# 8.[]组合的方式,只要满足中括号中的字符,就可以匹配
#text = "0731-88888888"
# '[\d\-]' 只能匹配一个字符
# '[\d\-]+' 可以匹配多个字符
#ret = re.match('[\d\-]+',text)
#print(ret.group())
# 8.1. 中括号的形式代替 \d
#text = "09"
# ^ : 非 0-9 间的字符
#ret = re.match('[^0-9]',text)
#print(ret.group())
# 8.2.中括号的形式替换 \D
#text = "a"
#ret = re.match('[^0-9]',text)
#print(ret.group())
# 8.3.中括号的形式替换 \w
#text = "b"
#ret = re.match('[a-zA-Z0-9_]',text)
#print(ret.group())
# 8.4.中括号的形式替换 \W
#text = "+"
#ret = re.match('[^a-zA-Z0-9_]',text)
#print(ret.group())
###########匹配多个字符########
# 9. *:可以匹配0或多个任意字符
#text = "0731"
#ret = re.match('\d*',text)
#print(ret.group())
# 10. +匹配一个或多个字符
#text = "0731"
#ret = re.match('\w+',text)
#print(ret.group())
# 11. ?匹配一个或0个(要么没有,要么就只有一个)
#text = "0731"
#ret = re.match('\w?',text)
#print(ret.group())
# 12. {m}: 匹配 m个字符
#text = "0731"
#ret = re.match('\w{2}',text)
#print(ret.group())
# 13. {m,n}:匹配 m-n个字符
#text = "0731"
#ret = re.match('\w{1,3}',text)
#print(ret.group())
############小案例##########
# 1.验证手机号码:
#text = "18578900987"
#ret = re.match('1[34578]\d{9}',text)
#print(ret.group())
# 2.验证邮箱:
#text = "hynever12_@qq.com"
# '\w+': 最少要有一个
# \w+@[a-z0-9]+\. \:转译
#ret = re.match('\w+@[a-z0-9]+\.[a-z]+',text)
#print(ret.group())
# 3.验证url:
#text = "https://baike.sogou.com/v58828.htm?fromTitle=Python"
# | 或
#ret = re.match('(http|https|ftp)://[^\s]+',text)
#print(ret.group())
# 4.验证身份证:
text = "31131118908123230x"
ret = re.match('\d{17}[\dxX]',text)
print(ret.group())