1. re.match() - 从字符串开头匹配
检查字符串开头是否符合模式,返回匹配对象或None。
import re
pattern = r"hello\s\w+"
result = re.match(pattern, "hello world")
if result:
print("匹配成功:", result.group()) # 输出: hello world
else:
print("匹配失败")
掌握文本处理的核心技能 - 从基础语法到高级应用
正则表达式(Regular Expression)是一种强大的文本模式匹配工具,使用特定语法规则来描述字符串的组成结构。在Python中,通过re
模块提供正则表达式支持。
正则表达式的主要用途包括:
元字符 | 描述 | 示例 |
---|---|---|
. |
匹配任意单个字符(换行符除外) | p.t 匹配 "pat", "pet", "p#t" 等 |
\d |
匹配数字字符 | \d\d 匹配 "42", "01" 等 |
\w |
匹配字母、数字或下划线 | \w+ 匹配 "hello", "var123" 等 |
\s |
匹配空白字符(空格、制表符等) | \s+ 匹配一个或多个空白字符 |
[] |
匹配括号内的任意字符 | [aeiou] 匹配任何元音字母 |
*+?{} |
匹配重复次数 | \d{3,5} 匹配3到5位数字 |
检查字符串开头是否符合模式,返回匹配对象或None。
import re
pattern = r"hello\s\w+"
result = re.match(pattern, "hello world")
if result:
print("匹配成功:", result.group()) # 输出: hello world
else:
print("匹配失败")
扫描整个字符串,返回第一个匹配项。
import re
text = "联系客服: 400-123-4567 或 555-1234"
pattern = r"\d{3}-\d{3}-\d{4}"
match = re.search(pattern, text)
if match:
print("找到电话号码:", match.group()) # 输出: 400-123-4567
返回字符串中所有匹配模式的子串列表。
import re
text = "苹果价格: ¥5.5, 香蕉价格: ¥3.2, 橙子价格: ¥4.8"
pattern = r"¥(\d+\.\d+)"
prices = re.findall(pattern, text)
print("所有价格:", prices) # 输出: ['5.5', '3.2', '4.8']
替换字符串中匹配正则表达式的部分。
import re
text = "今天是2023-08-15,明天是2023-08-16"
pattern = r"(\d{4})-(\d{2})-(\d{2})"
replacement = r"\2/\3/\1" # 将YYYY-MM-DD格式转换为MM/DD/YYYY
new_text = re.sub(pattern, replacement, text)
print(new_text) # 输出: 今天是08/15/2023,明天是08/16/2023
import re
def validate_email(email):
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
return re.match(pattern, email) is not None
print(validate_email("user@example.com")) # True
print(validate_email("invalid.email@")) # False
import re
text = "访问我们的网站: https://www.example.com 或 http://sub.domain.org/path"
pattern = r"https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+[/\w\.-]*"
urls = re.findall(pattern, text)
print("找到的URL:", urls)
# 输出: ['https://www.example.com', 'http://sub.domain.org/path']
import re
html = "<h1>标题</h1><p>第一段</p><p>第二段内容</p>"
pattern = r"<p>(.*?)</p>"
paragraphs = re.findall(pattern, html)
print("段落内容:", paragraphs) # 输出: ['第一段', '第二段内容']
import re
log = "2023-08-15 14:30:22 [INFO] User 'admin' logged in from 192.168.1.101"
pattern = r"(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) \[(\w+)\] (.+)"
match = re.match(pattern, log)
if match:
date, time, log_level, message = match.groups()
print(f"日期: {date}, 时间: {time}, 级别: {log_level}, 消息: {message}")
r
前缀,避免转义问题re.compile()
(?#注释)
或re.VERBOSE标志*?
、+?
进行非贪婪匹配
import re
# 使用re.VERBOSE允许添加注释和空白
pattern = re.compile(r"""
^(\d{3}) # 区号 (3位数字)
[\s-]? # 可选的分隔符(空格或短划线)
(\d{3,4}) # 前3或4位号码
[\s-]? # 可选的分隔符
(\d{4})$ # 最后4位号码
""", re.VERBOSE)
phone_numbers = [
"8001234567",
"800-123-4567",
"800 123 4567",
"8001234567"
]
for num in phone_numbers:
if pattern.match(num):
print(f"有效电话号码: {num}")
本文由DuguTuoYang于2025-08-02发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://521pj.cn/20257161.html
发表评论