Python re 库从入门到高阶用法详解
Python re 库详解:从入门到高阶
正则表达式是处理字符串的强大工具,Python 的re模块提供了对正则表达式的全面支持。本文将从基础到高阶详细讲解re库的使用,并通过实例帮助理解。
一、入门:正则表达式基础与 re 库核心函数
1. 基本概念
正则表达式是由普通字符和特殊字符 (元字符) 组成的字符串模式,用于匹配字符串。
2. 核心函数
2.1re.match()- 从字符串开头匹配
尝试从字符串的起始位置匹配一个模式,若匹配成功返回匹配对象,否则返回 None。
import re # 示例1:匹配成功 result = re.match(r'hello', 'hello world') print(result.group()) # 输出: hello # 示例2:匹配失败(不是从开头匹配) result = re.match(r'world', 'hello world') print(result) # 输出: None
练习题:验证一个字符串是否以字母开头
def starts_with_letter(s):
return bool(re.match(r'^[a-zA-Z]', s))
print(starts_with_letter("hello")) # True
print(starts_with_letter("123hello")) # False2.2re.search()- 在整个字符串中搜索匹配
扫描整个字符串并返回第一个成功的匹配。
import re # 示例:在整个字符串中查找 result = re.search(r'world', 'hello world') print(result.group()) # 输出: world
练习题:检查字符串中是否包含数字
def has_number(s):
return bool(re.search(r'\d', s))
print(has_number("hello123")) # True
print(has_number("helloworld")) # False2.3re.findall()- 找到所有匹配项
找到所有匹配的子串,并以列表形式返回。
import re # 示例:找到所有数字 result = re.findall(r'\d+', 'age: 25, score: 98, weight: 65') print(result) # 输出: ['25', '98', '65']
练习题:提取字符串中所有的邮箱地址
def extract_emails(s):
return re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', s)
text = "联系我们: info@example.com, 销售: sales@company.org"
print(extract_emails(text)) # ['info@example.com', 'sales@company.org']2.4re.sub()- 替换匹配项
替换字符串中所有匹配的子串。
import re # 示例:替换所有数字为* result = re.sub(r'\d+', '*', 'age: 25, score: 98') print(result) # 输出: age: *, score: *
练习题:将字符串中的敏感信息(电话)打码
def mask_phone(s):
return re.sub(r'1[3-9]\d{9}', '1xxxxxxxxx', s)
text = "我的电话是13812345678,他的电话是13987654321"
print(mask_phone(text)) # 我的电话是1xxxxxxxxx,他的电话是1xxxxxxxxx二、进阶:正则表达式元字符与模式
1. 常用元字符
元字符 | 描述 | |
| 匹配任意字符(除换行符) | |
| 匹配字符串开头 | |
| 匹配字符串结尾 | |
| 匹配前一个字符 0 次或多次 | |
| 匹配前一个字符 1 次或多次 | |
| 匹配前一个字符 0 次或 1 次 | |
| 匹配前一个字符恰好 n 次 | |
| 匹配前一个字符至少 n 次 | |
| 匹配前一个字符 n 到 m 次 | |
| 字符集,匹配其中任意一个字符 | |
` | ` | 匹配左右任意一个表达式 |
| 分组,将括号内的作为一个整体 |
2. 特殊序列
序列 | 描述 |
| 匹配任意数字,等价于 [0-9] |
| 匹配任意非数字 |
| 匹配任意空白字符 |
| 匹配任意非空白字符 |
| 匹配字母、数字、下划线 |
| 匹配非字母、数字、下划线 |
| 匹配单词边界 |
3. 实例练习
3.1 匹配 IP 地址
import re
def is_valid_ip(ip):
pattern = r'^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$'
return bool(re.match(pattern, ip))
print(is_valid_ip("192.168.1.1")) # True
print(is_valid_ip("256.0.0.1")) # False3.2 提取 HTML 标签内容
import re
def extract_tag_content(html, tag):
pattern = rf'<{tag}>(.*?)</{tag}>'
return re.findall(pattern, html, re.DOTALL)
html = '''
<div>第一部分</div>
<div>第二部分</div>
<p>这是段落</p>
'''
print(extract_tag_content(html, 'div')) # ['第一部分', '第二部分']三、高阶:编译正则表达式与高级特性
1.re.compile()- 编译正则表达式
编译正则表达式为模式对象,可提高多次使用的效率。
import re
# 编译正则表达式
pattern = re.compile(r'\d+')
# 使用编译后的模式
print(pattern.findall('age: 25, score: 98')) # ['25', '98']
print(pattern.sub('*', 'age: 25, score: 98')) # age: *, score: *2. 匹配对象的方法
当匹配成功时,match()和search()返回匹配对象,包含以下常用方法:
group(): 返回匹配的字符串start(): 返回匹配的起始位置end(): 返回匹配的结束位置span(): 返回匹配的起始和结束位置的元组
import re result = re.search(r'(\d+)-(\d+)-(\d+)', '今天是2023-10-05') print(result.group()) # 2023-10-05 print(result.group(1)) # 2023 print(result.group(2)) # 10 print(result.group(3)) # 05 print(result.span()) # (3, 13)
3. 贪婪与非贪婪匹配
正则表达式默认是贪婪的,会尽可能匹配最长的字符串。在量词后加?可启用非贪婪模式。
import re # 贪婪匹配 text = '<div>内容1</div><div>内容2</div>' print(re.findall(r'<div>(.*)</div>', text)) # ['内容1</div><div>内容2'] # 非贪婪匹配 print(re.findall(r'<div>(.*?)</div>', text)) # ['内容1', '内容2']
4. 标志参数
re模块的函数支持标志参数,常用的有:
re.IGNORECASE或re.I: 忽略大小写re.DOTALL或re.S: 使.匹配包括换行符在内的所有字符re.MULTILINE或re.M: 多行模式
import re # 忽略大小写 print(re.findall(r'hello', 'Hello HELLO hello', re.IGNORECASE)) # ['Hello', 'HELLO', 'hello'] # 多行模式 text = 'line1\nline2\nline3' print(re.findall(r'^line', text, re.MULTILINE)) # ['line', 'line', 'line']
5. 高阶练习题
5.1 解析 URL 参数
import re
def parse_url_params(url):
params = {}
# 提取参数部分
match = re.search(r'\?(.*)$', url)
if match:
param_str = match.group(1)
# 分割参数
param_list = re.split(r'&', param_str)
for param in param_list:
# 分割键值对
key_value = re.split(r'=', param, 1)
if len(key_value) == 2:
params[key_value[0]] = key_value[1]
return params
url = "https://example.com/search?query=python&page=2&sort=desc"
print(parse_url_params(url))
# {'query': 'python', 'page': '2', 'sort': 'desc'}5.2 验证密码强度
import re
def check_password_strength(password):
# 至少8个字符,包含大小写字母、数字和特殊字符
if len(password) < 8:
return "弱:密码长度不足8位"
strength = 0
if re.search(r'[A-Z]', password):
strength += 1
if re.search(r'[a-z]', password):
strength += 1
if re.search(r'\d', password):
strength += 1
if re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
strength += 1
if strength == 4:
return "强:密码强度良好"
elif strength >= 2:
return "中:密码强度一般"
else:
return "弱:密码组成太简单"
print(check_password_strength("123456")) # 弱:密码长度不足8位
print(check_password_strength("abcdefgh")) # 弱:密码组成太简单
print(check_password_strength("Abcdefgh")) # 中:密码强度一般
print(check_password_strength("Abcdefgh123")) # 中:密码强度一般
print(check_password_strength("Abc@12345")) # 强:密码强度良好四、总结
re库是 Python 处理字符串的强大工具,掌握它可以极大提高字符串处理效率。本文从基础函数到高级特性,涵盖了re库的主要用法:
- 入门:掌握
match()、search()、findall()、sub()等核心函数 - 进阶:熟悉元字符、特殊序列和常用模式
- 高阶:学会编译正则表达式、处理匹配对象、使用贪婪 / 非贪婪模式和标志参数
正则表达式的学习需要多练习,通过实际问题来加深理解和记忆。随着实践的增多,你会发现正则表达式在文本处理中的巨大价值。
到此这篇关于Python re 库详解:从入门到高阶的文章就介绍到这了,更多相关Python re 库内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!


最新评论