引言
正则表达式(Regular Expression,简称 regex 或 regexp)是一种强大的文本处理工具,它使用特定的字符序列来描述和匹配字符串模式。自从20世纪50年代由数学家斯蒂芬·科尔·克莱尼提出以来,正则表达式已经成为文本处理、数据验证、信息提取等领域不可或缺的工具。
在当今数据爆炸的时代,我们每天都需要处理大量的文本信息。无论是验证用户输入、从日志文件中提取关键信息,还是进行复杂的文本替换,正则表达式都能提供简洁而高效的解决方案。本文将带你从正则表达式的基础概念入手,逐步深入到复杂模式的应用,通过丰富的示例帮助你掌握这一强大的文本处理工具。
正则表达式基础
什么是正则表达式
正则表达式是一种由普通字符(如字母a到z)和特殊字符(称为”元字符”)组成的文字模式,用于描述在搜索文本时要匹配的一个或多个字符串。它就像一种专门用于字符串处理的微型语言,能够让你灵活地描述字符串的规则。
基本语法
字符匹配
最简单的正则表达式就是普通字符串,它只匹配自身。例如:
hello
这个正则表达式只会匹配字符串”hello”。
元字符
正则表达式的强大之处在于它提供了许多特殊字符(元字符),这些字符不匹配自身,而是有特殊的含义:
.
:匹配除换行符以外的任意单个字符
*
:匹配前面的元素零次或多次
+
:匹配前面的元素一次或多次
?
:匹配前面的元素零次或一次
^
:匹配字符串的开始位置
$
:匹配字符串的结束位置
[]
:字符集,匹配方括号中的任意一个字符
[^]
:否定字符集,匹配除了方括号中字符的任意字符
|
:或操作符,匹配左右两边的任意一个表达式
()
:分组,将括号内的表达式作为一个整体
{}
:量词,指定匹配次数
转义字符
如果要匹配元字符本身,需要使用反斜杠
\
进行转义。例如,要匹配点号
.
,需要写成
\.
。
简单模式示例
让我们通过一些简单的示例来理解正则表达式的基本用法:
1. 匹配特定单词
import re
text = “Hello world, hello Python, hello regex”
pattern = r”hello”
matches = re.findall(pattern, text, re.IGNORECASE) # 忽略大小写
print(matches) # 输出: [‘Hello’, ‘hello’, ‘hello’]
2. 匹配数字
import re
text = “I have 2 apples and 15 oranges”
pattern = r”\d+” # \d表示数字,+表示一次或多次
matches = re.findall(pattern, text)
print(matches) # 输出: [‘2′, ’15’]
3. 匹配单词边界
import re
text = “cat category concatenate”
pattern = r”\bcat\b” # \b表示单词边界
matches = re.findall(pattern, text)
print(matches) # 输出: [‘cat’]
4. 匹配邮箱地址
import re
text = “Contact us at support@example.com or info@example.org”
pattern = r”\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘support@example.com’, ‘info@example.org’]
数据验证应用
正则表达式在数据验证方面有着广泛的应用,特别是在表单验证、数据清洗等场景中。下面我们将介绍一些常见的数据验证示例。
邮箱验证
邮箱验证是Web开发中最常见的需求之一。一个基本的邮箱地址正则表达式可以如下:
import re
def validate_email(email):
pattern = r’^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$’
if re.match(pattern, email):
return True
return False
# 测试
emails = [
“user@example.com”, # 有效
“user.name@example.com”, # 有效
“user@sub.example.com”, # 有效
“user@example”, # 无效
“user.example.com”, # 无效
“@example.com”, # 无效
]
for email in emails:
print(f”{email}: {‘有效’ if validate_email(email) else ‘无效’}”)
电话号码验证
电话号码的格式因国家/地区而异,下面是一个验证美国电话号码的示例:
import re
def validate_us_phone(phone):
pattern = r’^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$’
if re.match(pattern, phone):
return True
return False
# 测试
phones = [
“(123) 456-7890”, # 有效
“123-456-7890”, # 有效
“123.456.7890”, # 有效
“1234567890”, # 有效
“+1 123 456 7890”, # 有效
“123 456 7890”, # 有效
“(123)456-7890”, # 有效
“123-4567”, # 无效
“12-3456-7890″, # 无效
]
for phone in phones:
print(f”{phone}: {‘有效’ if validate_us_phone(phone) else ‘无效’}”)
日期验证
日期验证需要考虑不同的格式,下面是一个验证YYYY-MM-DD格式日期的示例:
import re
def validate_date(date):
pattern = r’^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$’
if re.match(pattern, date):
return True
return False
# 测试
dates = [
“2023-05-15”, # 有效
“2023-12-31”, # 有效
“2023-02-28”, # 有效
“2023-13-01”, # 无效(月份)
“2023-00-15”, # 无效(月份)
“2023-05-32”, # 无效(日期)
“2023/05/15”, # 无效(格式)
“23-05-15″, # 无效(年份)
]
for date in dates:
print(f”{date}: {‘有效’ if validate_date(date) else ‘无效’}”)
密码强度验证
密码强度验证通常需要检查密码是否包含特定类型的字符,如下面的示例:
import re
def check_password_strength(password):
# 至少8个字符,至少1个大写字母,1个小写字母,1个数字和1个特殊字符
pattern = r’^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$’
if re.match(pattern, password):
return “强密码”
# 至少6个字符,包含字母和数字
pattern = r’^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$’
if re.match(pattern, password):
return “中等密码”
return “弱密码”
# 测试
passwords = [
“Password123!”, # 强密码
“Pass123”, # 中等密码
“password”, # 弱密码
“123456”, # 弱密码
“P@ssw0rd”, # 强密码
]
for password in passwords:
print(f”{password}: {check_password_strength(password)}”)
URL验证
URL验证需要考虑协议、域名、端口、路径等多个部分:
import re
def validate_url(url):
pattern = r’^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$’
if re.match(pattern, url):
return True
return False
# 测试
urls = [
“https://www.example.com”, # 有效
“http://example.com”, # 有效
“www.example.com”, # 有效
“example.com”, # 有效
“https://sub.example.com/path”, # 有效
“https://example.com:8080”, # 有效
“ftp://example.com”, # 无效(协议)
“https://example..com”, # 无效(域名)
“https://.com”, # 无效(域名)
]
for url in urls:
print(f”{url}: {‘有效’ if validate_url(url) else ‘无效’}”)
IP地址验证
IP地址验证需要考虑IPv4和IPv6两种格式:
import re
def validate_ipv4(ip):
pattern = r’^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$’
if re.match(pattern, ip):
return True
return False
def validate_ipv6(ip):
pattern = r’^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$’
if re.match(pattern, ip):
return True
return False
# 测试IPv4
ipv4_addresses = [
“192.168.1.1”, # 有效
“255.255.255.255”, # 有效
“0.0.0.0”, # 有效
“256.1.2.3”, # 无效
“192.168.1”, # 无效
“192.168.1.1.1”, # 无效
]
print(“IPv4地址验证:”)
for ip in ipv4_addresses:
print(f”{ip}: {‘有效’ if validate_ipv4(ip) else ‘无效’}”)
# 测试IPv6
ipv6_addresses = [
“2001:0db8:85a3:0000:0000:8a2e:0370:7334”, # 有效
“2001:db8:85a3:0:0:8a2e:370:7334”, # 有效
“2001:db8:85a3::8a2e:370:7334”, # 有效
“::1”, # 有效
“::”, # 有效
“2001::25de::cade”, # 无效
“2001:0db8:85a3::8a2e:0370:7334:extra”, # 无效
]
print(“\nIPv6地址验证:”)
for ip in ipv6_addresses:
print(f”{ip}: {‘有效’ if validate_ipv6(ip) else ‘无效’}”)
文本提取应用
正则表达式在文本提取方面也非常强大,可以从大量文本中快速提取所需信息。下面是一些常见的文本提取应用示例。
提取邮箱地址
从一段文本中提取所有邮箱地址:
import re
text = “””
Contact us at support@example.com for technical support.
For sales inquiries, email sales@company.com or contact our regional offices:
– North America: na@company.com
– Europe: eu@company.com
– Asia: asia@company.com
You can also reach us at info@company.org or feedback@company.net.
“””
pattern = r’\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b’
emails = re.findall(pattern, text)
print(“提取的邮箱地址:”)
for email in emails:
print(email)
提取URL
从文本中提取所有URL:
import re
text = “””
Visit our website at https://www.example.com for more information.
You can also check our blog at http://blog.example.com/posts/latest.
For downloads, go to ftp://files.example.com/downloads.
Our social media pages:
– Facebook: https://facebook.com/example
– Twitter: https://twitter.com/example
– LinkedIn: https://linkedin.com/company/example
“””
pattern = r’https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+[/\w .-]*\??[/\w .-]*’
urls = re.findall(pattern, text)
print(“提取的URL:”)
for url in urls:
print(url)
提取HTML标签内容
从HTML代码中提取特定标签的内容:
import re
html = “””
Welcome to Example
This is a paragraph.
This is another paragraph inside a div.
Link to Example
“””
# 提取所有标题
titles = re.findall(r’
print(“标题:”)
for title in titles:
print(title)
# 提取所有段落
paragraphs = re.findall(r’
(.*?)
‘, html)
print(“\n段落:”)
for p in paragraphs:
print(p)
# 提取所有链接
links = re.findall(r’(.*?)‘, html)
print(“\n链接:”)
for url, text in links:
print(f”URL: {url}, Text: {text}”)
提取JSON数据
从文本中提取JSON数据:
import re
import json
text = “””
Some text before JSON data.
{
“name”: “John Doe”,
“age”: 30,
“email”: “john@example.com”,
“address”: {
“street”: “123 Main St”,
“city”: “Anytown”,
“state”: “CA”,
“zip”: “12345”
},
“hobbies”: [“reading”, “hiking”, “coding”]
}
Some text after JSON data.
Another JSON object:
{
“product”: “Laptop”,
“price”: 999.99,
“in_stock”: true
}
More text.
“””
# 提取JSON对象
pattern = r’\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}’
json_strings = re.findall(pattern, text, re.DOTALL)
print(“提取的JSON数据:”)
for i, json_str in enumerate(json_strings, 1):
print(f”\nJSON对象 {i}:”)
try:
data = json.loads(json_str)
print(json.dumps(data, indent=2))
except json.JSONDecodeError:
print(“无效的JSON格式”)
提取数字和货币金额
从文本中提取数字和货币金额:
import re
text = “””
The company’s revenue was $1,234,567.89 last year, an increase of 15.7% from the previous year.
Expenses totaled €890,123.45, resulting in a net profit of ¥344,444.44.
The stock price is currently at $123.45 per share, with a market cap of $45.67 billion.
We expect to invest approximately £2.5 million in new equipment next quarter.
“””
# 提取所有数字(包括整数、小数、科学计数法)
numbers = re.findall(r’-?\d+(?:,\d+)*(?:\.\d+)?(?:[eE][+-]?\d+)?’, text)
print(“提取的数字:”)
for num in numbers:
print(num)
# 提取货币金额
currency_pattern = r'[$€£¥]\s?-?\d+(?:,\d+)*(?:\.\d+)?(?:\s[million|billion|trillion])?’
currencies = re.findall(currency_pattern, text)
print(“\n提取的货币金额:”)
for currency in currencies:
print(currency)
提取日期和时间
从文本中提取各种格式的日期和时间:
import re
text = “””
The meeting is scheduled for 2023-05-15 at 14:30.
Please submit your report by 15/05/2023.
The event will take place on May 20, 2023.
Office hours are 9:00 AM to 5:00 PM, Monday to Friday.
The deadline is 31-Dec-2023 at 11:59:59 PM.
“””
# 提取YYYY-MM-DD格式的日期
dates1 = re.findall(r’\d{4}-\d{2}-\d{2}’, text)
print(“YYYY-MM-DD格式的日期:”)
for date in dates1:
print(date)
# 提取DD/MM/YYYY格式的日期
dates2 = re.findall(r’\d{2}/\d{2}/\d{4}’, text)
print(“\nDD/MM/YYYY格式的日期:”)
for date in dates2:
print(date)
# 提取Month D, YYYY格式的日期
dates3 = re.findall(r'[A-Z][a-z]+ \d{1,2}, \d{4}’, text)
print(“\nMonth D, YYYY格式的日期:”)
for date in dates3:
print(date)
# 提取DD-MMM-YYYY格式的日期
dates4 = re.findall(r’\d{1,2}-[A-Z][a-z]{2}-\d{4}’, text)
print(“\nDD-MMM-YYYY格式的日期:”)
for date in dates4:
print(date)
# 提取时间(HH:MM格式)
times1 = re.findall(r’\d{1,2}:\d{2}’, text)
print(“\n时间(HH:MM格式):”)
for time in times1:
print(time)
# 提取时间(HH:MM:SS格式)
times2 = re.findall(r’\d{1,2}:\d{2}:\d{2}’, text)
print(“\n时间(HH:MM:SS格式):”)
for time in times2:
print(time)
日志分析应用
正则表达式在日志分析中非常重要,可以帮助我们从大量的日志数据中提取关键信息、识别错误模式、统计特定事件等。下面是一些日志分析的常见应用示例。
Apache访问日志分析
Apache访问日志通常包含访问者的IP、时间、请求方法、请求的URL、状态码等信息。下面是一个分析Apache访问日志的示例:
import re
from collections import Counter
# 示例Apache访问日志
apache_log = “””
192.168.1.100 – – [15/May/2023:12:30:45 +0000] “GET /index.html HTTP/1.1” 200 2326
192.168.1.101 – – [15/May/2023:12:31:02 +0000] “GET /about.html HTTP/1.1” 200 1547
192.168.1.102 – – [15/May/2023:12:31:15 +0000] “POST /login HTTP/1.1” 302 0
192.168.1.100 – – [15/May/2023:12:31:23 +0000] “GET /images/logo.png HTTP/1.1” 200 5432
192.168.1.103 – – [15/May/2023:12:31:45 +0000] “GET /admin HTTP/1.1” 403 1024
192.168.1.101 – – [15/May/2023:12:32:01 +0000] “GET /contact.html HTTP/1.1” 200 1876
192.168.1.104 – – [15/May/2023:12:32:15 +0000] “GET /nonexistent.html HTTP/1.1” 404 512
192.168.1.102 – – [15/May/2023:12:32:30 +0000] “GET /dashboard HTTP/1.1” 200 3456
“””
# Apache日志格式正则表达式
log_pattern = r'(\d+\.\d+\.\d+\.\d+) – – \[([^\]]+)\] “(\w+) ([^”]+)” (\d+) (\d+)’
# 解析日志条目
log_entries = re.findall(log_pattern, apache_log)
# 提取所有IP地址
ips = [entry[0] for entry in log_entries]
ip_counter = Counter(ips)
print(“访问次数最多的IP地址:”)
for ip, count in ip_counter.most_common():
print(f”{ip}: {count}次”)
# 提取所有HTTP状态码
status_codes = [entry[4] for entry in log_entries]
status_counter = Counter(status_codes)
print(“\nHTTP状态码统计:”)
for code, count in status_counter.most_common():
print(f”{code}: {count}次”)
# 提取所有请求的URL
urls = [entry[3] for entry in log_entries]
url_counter = Counter(urls)
print(“\n最常访问的URL:”)
for url, count in url_counter.most_common():
print(f”{url}: {count}次”)
# 提取所有错误请求(状态码4xx或5xx)
error_requests = [entry for entry in log_entries if entry[4].startswith(‘4’) or entry[4].startswith(‘5’)]
print(“\n错误请求:”)
for ip, timestamp, method, url, status, size in error_requests:
print(f”{timestamp} – {ip} – {method} {url} – {status}”)
Nginx错误日志分析
Nginx错误日志通常包含错误发生的时间、错误级别、错误信息等。下面是一个分析Nginx错误日志的示例:
import re
from collections import Counter
# 示例Nginx错误日志
nginx_error_log = “””
2023/05/15 12:30:45 [error] 1234#0: *12345 open() “/var/www/html/index.html” failed (2: No such file or directory), client: 192.168.1.100, server: example.com, request: “GET /index.html HTTP/1.1”, host: “example.com”
2023/05/15 12:31:02 [warn] 1234#0: *12346 a client request body is buffered to a temporary file /var/cache/nginx/client_body/0000000001, client: 192.168.1.101, server: example.com, request: “POST /upload HTTP/1.1”, host: “example.com”
2023/05/15 12:31:15 [error] 1234#0: *12347 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.1.102, server: example.com, request: “GET /api/data HTTP/1.1”, upstream: “http://127.0.0.1:8080/api/data”, host: “example.com”
2023/05/15 12:31:23 [error] 1234#0: *12348 upstream timed out (110: Connection timed out) while connecting to upstream, client: 192.168.1.103, server: example.com, request: “GET /api/slow HTTP/1.1”, upstream: “http://127.0.0.1:8080/api/slow”, host: “example.com”
2023/05/15 12:31:45 [crit] 1234#0: *12349 open() “/var/log/nginx/error.log” failed (13: Permission denied), client: 192.168.1.104, server: example.com, request: “GET /admin/logs HTTP/1.1”, host: “example.com”
“””
# Nginx错误日志格式正则表达式
error_log_pattern = r'(\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}) \[(\w+)\] (\d+)#(\d+): \*(\d+) (.+?), client: (\d+\.\d+\.\d+\.\d+), server: ([^,]+), request: “([^”]+)”‘
# 解析日志条目
log_entries = re.findall(error_log_pattern, nginx_error_log)
# 提取所有错误级别
error_levels = [entry[1] for entry in log_entries]
level_counter = Counter(error_levels)
print(“错误级别统计:”)
for level, count in level_counter.most_common():
print(f”{level}: {count}次”)
# 提取所有错误信息
error_messages = [entry[5] for entry in log_entries]
print(“\n错误信息:”)
for message in error_messages:
print(f”- {message}”)
# 提取所有客户端IP
client_ips = [entry[6] for entry in log_entries]
ip_counter = Counter(client_ips)
print(“\n错误最多的客户端IP:”)
for ip, count in ip_counter.most_common():
print(f”{ip}: {count}次”)
应用程序日志分析
应用程序日志通常包含不同级别的日志消息,如INFO、WARNING、ERROR等。下面是一个分析应用程序日志的示例:
import re
from collections import Counter
# 示例应用程序日志
app_log = “””
2023-05-15 12:30:45,123 INFO [main] Application started successfully
2023-05-15 12:31:02,456 DEBUG [worker] Processing task #12345
2023-05-15 12:31:15,789 INFO [worker] Task #12345 completed successfully
2023-05-15 12:31:23,012 WARN [scheduler] No tasks scheduled for the next hour
2023-05-15 12:31:45,345 ERROR [database] Connection to database failed: Connection timed out
2023-05-15 12:32:01,678 INFO [database] Reconnected to database successfully
2023-05-15 12:32:15,901 ERROR [worker] Task #12346 failed with exception: NullPointerException
2023-05-15 12:32:30,234 INFO [scheduler] Scheduled 5 tasks for the next hour
“””
# 应用程序日志格式正则表达式
app_log_pattern = r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}) (\w+) \[([^\]]+)\] (.+)’
# 解析日志条目
log_entries = re.findall(app_log_pattern, app_log)
# 提取所有日志级别
log_levels = [entry[1] for entry in log_entries]
level_counter = Counter(log_levels)
print(“日志级别统计:”)
for level, count in level_counter.most_common():
print(f”{level}: {count}次”)
# 提取所有日志来源
log_sources = [entry[2] for entry in log_entries]
source_counter = Counter(log_sources)
print(“\n日志来源统计:”)
for source, count in source_counter.most_common():
print(f”{source}: {count}次”)
# 提取所有错误消息
error_entries = [entry for entry in log_entries if entry[1] in (‘ERROR’, ‘WARN’)]
print(“\n错误和警告消息:”)
for timestamp, level, source, message in error_entries:
print(f”{timestamp} [{level}] {source}: {message}”)
系统日志分析
系统日志(syslog)通常包含系统事件、服务状态等信息。下面是一个分析系统日志的示例:
import re
from collections import Counter
# 示例系统日志
syslog = “””
May 15 12:30:45 server01 kernel: [ 0.000000] Linux version 5.4.0-42-generic (buildd@lcy01-amd64-013) (gcc version 9.3.0 (Ubuntu 9.3.0-10ubuntu2)) #46-Ubuntu SMP Fri Jul 10 07:21:24 UTC 2020 (Ubuntu 5.4.0-42.46-generic 5.4.44)
May 15 12:31:02 server01 systemd[1]: Started Load/Save Random Seed.
May 15 12:31:15 server01 NetworkManager[845]:
May 15 12:31:23 server01 systemd[1]: Started Login Service.
May 15 12:31:45 server01 sshd[1234]: Server listening on 0.0.0.0 port 22.
May 15 12:32:01 server01 systemd[1]: Started Permit User Sessions.
May 15 12:32:15 server01 cron[1567]: (CRON) INFO (pidfile fd = 3)
May 15 12:32:30 server01 kernel: [ 1.234567] USB disconnect, address 1
May 15 12:32:45 server01 systemd[1]: Started Update UTMP about System Boot/Shutdown.
“””
# 系统日志格式正则表达式
syslog_pattern = r'(\w{3} \d{1,2} \d{2}:\d{2}:\d{2}) (\w+) ([^:]+): (.+)’
# 解析日志条目
log_entries = re.findall(syslog_pattern, syslog)
# 提取所有主机名
hostnames = [entry[1] for entry in log_entries]
hostname_counter = Counter(hostnames)
print(“主机名统计:”)
for hostname, count in hostname_counter.most_common():
print(f”{hostname}: {count}次”)
# 提取所有进程/服务名
processes = [entry[2] for entry in log_entries]
process_counter = Counter(processes)
print(“\n进程/服务统计:”)
for process, count in process_counter.most_common():
print(f”{process}: {count}次”)
# 提取所有内核消息
kernel_messages = [entry[3] for entry in log_entries if entry[2] == ‘kernel’]
print(“\n内核消息:”)
for message in kernel_messages:
print(f”- {message}”)
安全日志分析
安全日志通常包含认证尝试、访问控制、安全事件等信息。下面是一个分析安全日志的示例:
import re
from collections import Counter
# 示例安全日志
security_log = “””
2023-05-15 12:30:45,123 INFO [auth] User ‘admin’ logged in successfully from 192.168.1.100
2023-05-15 12:31:02,456 WARN [auth] Failed login attempt for user ‘admin’ from 192.168.1.101 – Invalid password
2023-05-15 12:31:15,789 INFO [auth] User ‘john’ logged in successfully from 192.168.1.102
2023-05-15 12:31:23,012 ERROR [auth] Multiple failed login attempts for user ‘admin’ from 192.168.1.101 – Account locked
2023-05-15 12:31:45,345 WARN [access] Unauthorized access attempt to ‘/admin’ from 192.168.1.103
2023-05-15 12:32:01,678 INFO [auth] User ‘jane’ logged in successfully from 192.168.1.104
2023-05-15 12:32:15,901 ERROR [auth] Brute force attack detected from 192.168.1.105 – IP blocked
2023-05-15 12:32:30,234 WARN [access] Suspicious activity detected from 192.168.1.106 – Multiple requests to sensitive endpoints
“””
# 安全日志格式正则表达式
security_log_pattern = r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}) (\w+) \[([^\]]+)\] (.+)’
# 解析日志条目
log_entries = re.findall(security_log_pattern, security_log)
# 提取所有安全事件类型
event_types = [entry[1] for entry in log_entries]
event_counter = Counter(event_types)
print(“安全事件类型统计:”)
for event_type, count in event_counter.most_common():
print(f”{event_type}: {count}次”)
# 提取所有安全模块
security_modules = [entry[2] for entry in log_entries]
module_counter = Counter(security_modules)
print(“\n安全模块统计:”)
for module, count in module_counter.most_common():
print(f”{module}: {count}次”)
# 提取所有失败的登录尝试
failed_logins = [entry for entry in log_entries if ‘Failed login’ in entry[3]]
print(“\n失败的登录尝试:”)
for timestamp, level, module, message in failed_logins:
print(f”{timestamp}: {message}”)
# 提取所有可疑IP
suspicious_ips = []
for entry in log_entries:
ip_match = re.search(r'(\d+\.\d+\.\d+\.\d+)’, entry[3])
if ip_match and (‘attack’ in entry[3] or ‘suspicious’ in entry[3] or ‘unauthorized’ in entry[3].lower()):
suspicious_ips.append(ip_match.group(1))
ip_counter = Counter(suspicious_ips)
print(“\n可疑IP地址:”)
for ip, count in ip_counter.most_common():
print(f”{ip}: {count}次可疑活动”)
高级正则表达式技巧
在掌握了正则表达式的基础知识后,我们可以学习一些高级技巧,以构建更复杂、更高效的正则表达式模式。
贪婪匹配与懒惰匹配
默认情况下,正则表达式中的量词(如
*
、
+
、
?
、
{n,m}
)是”贪婪”的,它们会尽可能多地匹配字符。有时我们需要”懒惰”匹配,即尽可能少地匹配字符。懒惰匹配通过在量词后添加
?
来实现。
import re
html = “
”
# 贪婪匹配 – 匹配尽可能多的字符
greedy_pattern = r’
‘
greedy_match = re.search(greedy_pattern, html)
print(“贪婪匹配结果:”, greedy_match.group(0))
# 懒惰匹配 – 匹配尽可能少的字符
lazy_pattern = r’
‘
lazy_match = re.search(lazy_pattern, html)
print(“懒惰匹配结果:”, lazy_match.group(0))
# 使用findall找出所有匹配
all_matches = re.findall(lazy_pattern, html)
print(“所有匹配结果:”, all_matches)
前瞻和后顾
前瞻(lookahead)和后顾(lookbehind)是正则表达式的高级特性,它们允许你匹配一个位置,这个位置的前面或后面必须满足某种模式,但不包括在匹配结果中。
正向前瞻(Positive Lookahead)
(?=…)
表示正向前瞻,它要求匹配位置后面必须跟有指定的模式。
import re
text = “apple banana orange grape”
# 匹配后面跟着” banana”的单词
pattern = r’\w+(?= banana)’
matches = re.findall(pattern, text)
print(“正向前瞻匹配结果:”, matches) # 输出: [‘apple’]
负向前瞻(Negative Lookahead)
(?!…)
表示负向前瞻,它要求匹配位置后面不能跟有指定的模式。
import re
text = “apple banana orange grape”
# 匹配后面不跟着” banana”的单词
pattern = r’\w+(?! banana)’
matches = re.findall(pattern, text)
print(“负向前瞻匹配结果:”, matches) # 输出: [‘appl’, ‘banana’, ‘orang’, ‘grape’]
正向后顾(Positive Lookbehind)
(?<=...)
表示正向后顾,它要求匹配位置前面必须有指定的模式。
import re
text = "apple banana orange grape"
# 匹配前面有"apple "的单词
pattern = r'(?<=apple )\w+'
matches = re.findall(pattern, text)
print("正向后顾匹配结果:", matches) # 输出: ['banana']
负向后顾(Negative Lookbehind)
(?Content