python正则表达式相关
正则表达式
导入模块 ipmort re
方法 re.findall()
data_list = re.findall("wq", text)
data_list = re.findall("[abc]", text) # 匹配a或b或c
data_list = re.findall("v[abc]", text) # 匹配以v开始a或b或c结尾的
data_list = re.findall("v[……abc]", text) # 匹配不以v开始a或b或c结尾的 ^取反
data_list = re.findall([0-9], text) # 匹配0-9的任意字符 [a-z]
.
代指除换行符以外的任意字符。
import re
text = "alexraotrootadmin"
data_list = re.findall("r.o", text)
data_list = re.findall("r.+o", text) # 贪婪匹配
data_list = re.findall("r.+?o", text) # 非贪婪匹配
print(data_list) # ['rao', 'roo']
\w
匹配字母或数字或下划线
data_list = re.findall("武\w+x", text)
\d
匹配数字
data_list = re.findall("d\d+", text)
\s
代指任意的空白符,包括空格、制表符等。
data_list = re.findall("a\w+\s\w+", text)
*
重复0次或更多次
+
重复1次或更多次
?
重复0次或1次
{n}
重复n次
{n,}
重复n次或更多次
{n,m}
重复n到m次
括号(分组)
data_list = re.findall("15131(2\d{5})", text) # 取以15131开头并且是(以2开头后面5位数字的值) 取()中的值 ['255789']
身份证号
import re
text = "dsf130429191912015219k13042919591219521Xkk"
data_list = re.findall("(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)", text)
print(data_list) # [('130429', '1919', '12', '01', '521', '9'), ('130429', '1959', '12', '19', '521', 'X')]
邮箱
import re
text = "楼主太牛逼了,在线想要 442662578@qq.com和xxxxx@live.com谢谢楼主,手机号也可15131255789,搞起来呀"
email_list = re.findall("\w+@\w+\.\w+", text, re.ASCII)
print(email_list) # ['442662578@qq.com', 'xxxxx@live.com']
^
开始
$
结束
实例:校验用户输入的邮箱格式是否正确
import re
text = input("请输入邮箱:")
email = re.findall("^\w+@\w+.\w+$", text, re.ASCII)
if not email:
print("邮箱格式错误")
else:
print(email)
特殊字符 * . \ { } ( )
查找特殊字符时要转义
本文来自博客园,作者:wq512,转载请注明原文链接:https://www.cnblogs.com/wangqi512/p/15186973.html