目录
正则表达式及re模块
re 模块
match 函数
- 尝试用正则表达式模式从字符串的 开头匹配,如果匹配成功,则返回一个匹配对象;否则返回 None
案例:使用match函数匹配字符串
import re
# 1. re.match(正则字符串, 目标字符串):
# 判断目标字符串是不是以正则匹配到的内容开头,如果成功,返回匹配对象;否则,返回None
# \d: 表示一个数字字符串 "0123456789"
# {3}: 表示连续出现3次 \d{3}: 连续出现的三个数字
result01 = re.match("\d{3}", "123aavvfdfsf")
print(result01) # <_sre.SRE_Match object; span=(0, 3), match='123'>
print(result01.group()) # 获取匹配到的字符串 123
search 函数
- 在字符串中查找正则表达式模式的第一次出现,如果匹配成功,则返回一个匹配对象;否则返回 None。
案例
import re
# 2. re.search(正则字符串, 目标字符串):
# 在字符串中查找正则表达式匹配的第一次出现, 如果成功,返回匹配对象;否则,返回None
result02 = re.search("\d{3}", "abc666def456qqq")
print(result02) # <_sre.SRE_Match object; span=(3, 6), match='666'>
print(result02.group()) # 获取匹配到的字符串 666
findall 函数
- 在字符串中查找正则表达式模式的所有出现;返回一个匹配对象的列表
案例
import re
# 3. re.findall(正则字符串, 目标字符串):
# 在字符串中查找正则表达式匹配的所有出现;返回一个匹配字符串的列表
result03 = re.findall("\d{3}", "abc666def456qqq")
print(result03) # ['666', '456']
finditer函数
- 查找字符串中所有匹配字符【返回迭代器】
案例
import re
# 4. re.finditer(正则字符串, 目标字符串): 查找正则字符串中所有匹配字符【返回可迭代对象】
result04 = re.finditer("\d{3}", "abc666def456qqq")
for item in result04:
print(item)
print(item.group())
split 方法
- 根据正则表达式中的分隔符把字符分割为一个列表,并返回成功匹配的列表
- 字符串也有类似的方法,但是正则表达式更加灵活
案例
import re
# 5. re.split(正则字符串, 目标字符串)
# 根据正则表达式中的分隔符把字符分割为一个列表,并返回成功分割的列表
result05 = re.split("-|\.", "hello-tar.gz")
print(result05) # ['hello', 'tar', 'gz']
sub方法
- 把字符串中所有匹配正则表达式的地方替换成新的字符串
import re
# 6. re.sub(正则字符串,替换字符串,目标字符串)
result06 = re.sub("\d{3}", "benben", "Hi~123, nice to meet you, 456")
print(result06) # Hi~benben, nice to meet you, benben
compile函数
- 对正则表达式模式进行编译,返回一个正则表达式对象
- 不是必须要用这种方式,但是在大量匹配的情况下,可以提升效率
案例
import re
# 7. re.compile(正则字符串): 将字符串编译成正则对象
patt_obj = re.compile("\d{3}") # patt_obj: 正则对象
# 一次编译多次匹配
result07 = patt_obj.search("abc666def456qqq")
print(result07) # <_sre.SRE_Match object; span=(3, 6), match='666'>
print(result07.group()) # 666
result08 = patt_obj.split("abc123qwer890aaa")
print(result08) # ['abc', 'qwer', 'aaa']
练习:分析 apache 访问日志
需求:编写一个apache 日志分析脚本(count_patt.py):
- 统计每个客户端访问 apache 服务器的次数
- 将统计信息通过字典的方式显示出来
- 分别统计客户端是 Firefox 和 MSIE 的访问次数
第一步:创建新的python文件count_patt.py,使用正则表达式过滤出IP地址和浏览器
import re #导入正则表达式的模块re
def count_patt(fname, patt): #函数count_patt(), 功能:分析apache访问日志
pass
if __name__ == '__main__':
fname = '/root/access_log' #指定文件名
ip = '(\d+\.){3}\d+' #使用正则匹配出IP地址
br = 'Chrome|MSIE|Firefox' #使用正则匹配出浏览器
result1 = count_patt(fname, ip) #统计文件中的IP地址的个数
result2 = count_patt(fname, br) #统计文件中的浏览器的个数
print(result1) #打印result1
print(result2)
第二步:编写函数count_patt()
import re #导入正则表达式的模块res
def count_patt(fname, patt): #函数count_patt(), 功能:分析apache访问日志
patt_dict = {
} #定义字典,存储结果数据
cpatt = re.compile(patt) #编译正则表达式【这里指: IP或br】
with open(fname, mode="r") as fobj: #以字符类型打开文件,遍历行
for line in fobj.readlines():
m = cpatt.search(line) #使用正则cpatt匹配line中的字符
if m: #当行line中正则匹配成功时
key = m.group() #获取在行line中匹配到的内容
if key not in patt_dict:
patt_dict[key] = 1
else:
patt_dict[key] += 1
return patt_dict
if __name__ == '__main__':
fname = '/root/access_log' #指定文件名
ip = '(\d+\.){3}\d+' #使用正则匹配出IP地址
br = 'Chrome|MSIE|Firefox' #使用正则匹配出浏览器
result1 = count_patt(fname, ip) #统计文件中的IP地址的个数
result2 = count_patt(fname, br) #统计文件中的浏览器的个数
print(result1) #打印result1【IP地址出现的次数】
print(result2) #打印result2【不同浏览器出现的次数】
# 测试分析apache访问日志的程序
[root@localhost xxx]# python3 count_patt.py