本文目录导读:

我来详细介绍Python正则表达式检索字符的各种案例:
基础检索方法
使用 re.search() - 查找第一个匹配
import re
text = "我的电话是 138-1234-5678,备用电话 139-8765-4321"
# 查找电话号码
result = re.search(r'\d{3}-\d{4}-\d{4}', text)
if result:
print(f"找到号码: {result.group()}") # 138-1234-5678
使用 re.findall() - 查找所有匹配
text = "我的邮箱是 test1@example.com 和 test2@gmail.com"
# 查找所有邮箱地址
emails = re.findall(r'[\w.]+@\w+\.\w+', text)
print(f"所有邮箱: {emails}") # ['test1@example.com', 'test2@gmail.com']
使用 re.finditer() - 迭代查找
text = "编号: A001, B002, C003"
# 查找所有编号并获取位置
for match in re.finditer(r'[A-Z]\d{3}', text):
print(f"找到: {match.group()}, 位置: {match.span()}")
# 找到: A001, 位置: (4, 8)
# 找到: B002, 位置: (10, 14)
# 找到: C003, 位置: (16, 20)
特定字符检索案例
查找数字
text = "价格: $19.99, 折扣: 15%, 库存: 200件"
# 查找所有数字(含小数)
numbers = re.findall(r'\d+\.?\d*', text)
print(f"数字: {numbers}") # ['19.99', '15', '200']
# 查找整数
integers = re.findall(r'\b\d+\b', text)
print(f"整数: {integers}") # ['15', '200']
查找英文字母
text = "Hello123World! 你好"
# 查找所有英文字母
letters = re.findall(r'[a-zA-Z]+', text)
print(f"英文字母单词: {letters}") # ['Hello', 'World']
# 查找连续的大写字母
upper = re.findall(r'[A-Z]+', text)
print(f"大写字母: {upper}") # ['H', 'W']
查找中文
text = "Python正则表达式匹配中文字符案例"
# 查找所有中文
chinese = re.findall(r'[\u4e00-\u9fff]+', text)
print(f"中文: {chinese}") # ['正则表达式匹配中文字符案例']
# 查找特定模式的词
words = re.findall(r'中[文字]', text)
print(f"'中文'或'中字': {words}") # ['中文']
实际应用案例
提取URL
text = """访问我们的网站 https://www.example.com
或 http://blog.example.com/page?id=1"""
# 查找所有URL
urls = re.findall(r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', text)
print(f"URLs: {urls}")
# ['https://www.example.com', 'http://blog.example.com']
提取HTML标签内容
html = '<div class="content">重要通知</div><p>段落内容</p>'
# 提取标签内的文字
content = re.findall(r'<[^>]+>([^<]+)</[^>]+>', html)
print(f"标签内容: {content}") # ['重要通知', '段落内容']
验证密码强度
def check_password(password):
# 至少8位,包含大写字母、小写字母、数字、特殊字符
pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$'
if re.search(pattern, password):
return "密码强度达标"
else:
# 显示缺少的内容
missing = []
if not re.search(r'[a-z]', password):
missing.append("小写字母")
if not re.search(r'[A-Z]', password):
missing.append("大写字母")
if not re.search(r'\d', password):
missing.append("数字")
if not re.search(r'[@$!%*?&]', password):
missing.append("特殊字符")
return f"缺少: {', '.join(missing)}"
print(check_password("Abc123!@")) # 密码强度达标
print(check_password("abc123")) # 缺少: 大写字母, 特殊字符
高级检索技巧
使用捕获组提取特定部分
text = "日期: 2024-01-15, 重要程度: 高"
# 提取日期各部分
pattern = r'(\d{4})-(\d{2})-(\d{2})'
match = re.search(pattern, text)
if match:
year, month, day = match.groups()
print(f"年: {year}, 月: {month}, 日: {day}")
使用非贪婪匹配
text = "<h1>标题1</h1><h2>标题2</h2>"
# 贪婪匹配
greedy = re.findall(r'<.*>', text)
print(f"贪婪: {greedy}") # ['<h1>标题1</h1><h2>标题2</h2>']
# 非贪婪匹配
non_greedy = re.findall(r'<.*?>', text)
print(f"非贪婪: {non_greedy}") # ['<h1>', '</h1>', '<h2>', '</h2>']
实战:文本清洗
def clean_text(text):
"""文本清洗示例"""
# 1. 移除HTML标签
text = re.sub(r'<[^>]+>', '', text)
# 2. 替换多个空格为单个
text = re.sub(r'\s+', ' ', text)
# 3. 移除特殊字符(保留中文、英文、数字)
text = re.sub(r'[^\w\u4e00-\u9fff\s]', '', text)
# 4. 移除首尾空白
text = text.strip()
return text
# 测试
dirty_text = "<p>Hello 世界! @2024年</p> <br>新年\n快乐!"
clean = clean_text(dirty_text)
print(f"清洗前: {dirty_text}")
print(f"清洗后: {clean}")
这些案例涵盖了Python正则表达式检索字符的主要场景,你可以根据实际需求组合使用,记住使用r''原始字符串可以避免转义字符的问题。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播