Python正则表达式与文本处理

约 2 分钟读完

Python正则表达式与文本处理

re 模块基础

正则表达式是安全分析中最重要的文本处理工具,广泛用于日志分析、漏洞检测、数据提取。

常用函数

  • re.findall(pattern, text) — 查找所有匹配
  • re.search(pattern, text) — 查找第一个匹配
  • re.sub(pattern, repl, text) — 替换匹配内容

安全领域常用正则

import re

# 匹配IP地址
ip_pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'

# 匹配邮箱
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'

# 匹配URL
url_pattern = r'https?://[^\s<>"]+'

# 匹配SQL注入特征
sqli_pattern = r'(union|select|from|where|or\s+1=1|--)'

日志分析实战

# 从Web日志中提取所有IP
with open('access.log') as f:
    ips = re.findall(ip_pattern, f.read())
    from collections import Counter
    for ip, count in Counter(ips).most_common(10):
        print(f"{ip}: {count}")

总结

正则表达式是安全日志分析的利器。建议将常用正则模式整理成工具库,方便日常使用。

← Python爬虫与数据采集 Python安全编程入门 →