最近使用Python正则表达式处理数据较多,先将Python使用正则表达式匹配文本的示例程序整理一下。
基本语法
基本语法与变量使用参考一下两个网站:
示例程序
从文件中读取内容,使用正则表达式匹配
import re
import sys
'''
主函数
'''
# 重定向输出位置
output = sys.stdout
outputfile = open('test.txt', 'w')
sys.stdout = outputfile
IDXfile = open('mytest.html', 'r', encoding='utf-8') # gbk 格式的文件 IDXfile.read() 会报错,以 utf-8 格式打开就行
fileread = IDXfile.read()
IDXfile.close()
# 编译正则表达式
pattern = re.compile(
r'<table[\s]*([\w]*)>',
re.M);
# 匹配
myTable = re.findall(pattern, fileread)
myTable = myTable[0] # pattern 中 () 为元组,按照从左到右的顺序从 0 开始编号,每个编号对应()中匹配的内容
# print(myTable)
# 筛选出所有权限
pattern2 = re.compile(
r'#这里写正则表达式',
re.M
);
# 匹配
myPerTable = re.findall(pattern2, myTable)
# 输出匹配结果
print(len(myPerTable))
for tmp in myPerTable:
print(tmp)
# 关闭输出重定向
outputfile.close()
sys.stdout = output