正则表达式re模块
导包
import re
s = "python java c c++ python2 python python3"
match 从头匹配
res = re.match("python", s)
res_2 = re.match("python2", s)
print("res:", res)
print(res.span())
print(res.group())
print("res_2:", res_2)
search 搜索匹配
res_3 = re.search("python3", s)
print("res_3:", res_3)
findall 搜索全部匹配,返回列表
res_4 = re.findall("python", s)
print("res_4:", res_4)
匹配数字,\前面加r表示转义字符无效
res_5 = re.findall(r"\d", s)
print(res_5)
匹配非单词字符
res_6 = re.findall(r"\W", s)
print(res_6)
匹配英文字母
res_7 = re.findall(r"[a-zA-Z]", s)
print(res_7)
案例、
匹配账号,字母数字组成,长度6-10:注意{6,9}此处无空格
r = r"^[a-zA-Z0-9]{6,9}$"
s = "12345Az"
print(re.findall(r, s))
匹配qq号,纯数字,首位非0,长度6-11
r = r"^[1-9][0-9]{5,10}$"
r_1 = r"[1-9][0-9]{5,10}"
s = "279968894"
print(re.match(r_1, s))
print(re.findall(r, s))
匹配邮箱,qq,163,gmail
注意此处整体需加括号,否则findall返回每个分组内容
# 注意此处整体需加括号,否则findall返回每个分组内容
r = r"(^[\w-]+(\.[\w-]+)*@(qq|163|gmail)(\.[\w-]+)+$)"
# s = "279968895@qq.com"
s = "a.asd.123.a_@gmail.psts.edu.cn"
print(re.findall(r, s))
print(re.match(r, s))
# 使用match取出邮箱
print(re.match(r, s).group())