正则表达式
 
基础
 
# 正则表达式
import re
s = "python itcast"
# match 从头开始匹配 头部不匹配返回None
result = re.match("python", s)
print(result)
print(result.span())
print(result.group())
# search 从开头找到结尾搜索,找到第一个就停止
s = "1python itcast python"
result = re.search("python", s)
print(result)
# findall 搜索全部匹配的
result = re.findall("python", s)
print(result) 
 
元字符匹配
 
| 字符 | 功能 | 
|---|
| . | 匹配任意1个字符(除\n),\ .匹配. | 
| [] | 匹配中括号中的所有字符 | 
| \d | 匹配数字 | 
| \D | 匹配非数字 | 
| \s | 匹配空白 | 
| \S | 匹配非空白 | 
| \w | 匹配单词字符小写大写数字下划线 | 
| \W | 匹配非单词字符,即特殊字符 | 
 
 
数量匹配
 
| 字符 | 功能 | 
|---|
| * | 匹配前一个字符出现0-∞次 | 
| + | 匹配前一个字符出现1-∞次 | 
| ? | 匹配前一个字符出现0或1次 | 
| {m} | 匹配前一个字符出现m次 | 
| {m,} | 匹配前一个字符最少m次 | 
| {m,n} | 匹配前一个字符出现m到n次 | 
| ^ | 匹配字符串开头 | 
| $ | 匹配字符串结尾 | 
| \b | 匹配一个单词的边界 | 
| \B | 匹配非单词边界 | 
| | | 匹配左右任意一个表达式 | 
| () | 将括号中的字符作一个分组 | 
 
# 元字符匹配
s = "itcast1 @@python2 !!666 ##itheima3"
# 找出全部数字
result = re.findall(r'\d', s)    # r代表字符串里转义字符无效
print(result)
result = re.findall(r'\W', s)
print(result)
result = re.findall(r'[a-zA-Z0-9]', s)
print(result)
# 匹配账号,只能由字母和数字组成,6-10位
r = '^[0-9a-zA-Z]{6,10}$'   # ^和$表示从头到位匹配
s = '124211'
result = re.findall(r, s)
print(result)
# 匹配QQ号,纯数字,长度5-11,第一位不为0
r = '[1-9][0-9]{4,10}'  # 因为第一位已经占一位了
s = '012345678'
print(re.findall(r, s))    # 这里判断的是字串,所以有结果
# 匹配邮箱地址
r = '([\w-]+(\.[\w-]+)*@(qq|163|gmail)(\.[\w-]+)+)'    # 小括号+‘*’表示这组内容出现几次都行
# 整体括号是因为findall方法只会输出组,所以要变成一个组
s = 'a.b.c.d.e.f.g@qq.com.a.cn'
print(re.findall(r, s)) 
 
递归
 
# 递归
# 通过递归找出一个指定文件夹的全部文件
import os
def test_os():print(os.listdir("D:/test"))   # 列出路径下的内容print(os.path.isdir("D:/test"))   # 判断指定路径是不是文件夹print(os.path.exists("D:/test"))   # 判断指定路径是否存在file_list = []
def get_files(path):if os.path.isdir(path):for f in os.listdir(path):new_path = path + "/" + fif os.path.isdir(new_path):get_files(new_path)else:file_list.append(new_path)else:print("路径不存在")return []return file_list