答案:Python中使用re模块处理正则表达式,常用方法有re.match()从开头匹配、re.search()查找第一个匹配、re.fullmatch()完全匹配整个字符串、re.findall()返回所有匹配结果,可通过compile()编译正则提升效率,适用于验证手机号、邮箱等格式。

在 Python 中,可以使用 re 模块来处理正则表达式(Regular Expression),用于检验字符串是否符合某种模式。下面介绍常用方法和实际用法。
导入 re 模块
Python 自带 re 模块,使用前需要先导入:import re
常用方法检验字符串
re 模块提供了多个函数来匹配和检验字符串,最常用的有:
- re.match():从字符串**开头**匹配,如果开头不匹配则返回 None
- re.search():扫描整个字符串,返回第一个匹配结果
- re.fullmatch():整个字符串必须完全匹配指定模式
- re.findall():返回所有匹配的子串列表(可用于验证是否存在多个匹配)
基本使用示例
1. 使用 re.match() 检查是否以特定内容开头
立即学习“Python免费学习笔记(深入)”;
pattern = r'^\d+' # 匹配以数字开头的字符串
text = "123abc"
if re.match(pattern, text):
print("字符串以数字开头")
2. 使用 re.search() 检查是否包含某模式
pattern = r'\d+' # 匹配任意连续数字
text = "abc123def"
if re.search(pattern, text):
print("字符串中包含数字")
3. 使用 re.fullmatch() 验证完整格式(如手机号、邮箱)
phone_pattern = r'^1[3-9]\d{9}$' # 简化版中国大陆手机号
phone = "13812345678"
if re.fullmatch(phone_pattern, phone):
print("手机号格式正确")
else:
print("手机号格式错误")
4. 验证邮箱格式示例
email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
email = "user@example.com"
if re.fullmatch(email_pattern, email):
print("邮箱格式正确")
编译正则表达式(提高效率)
如果同一个正则要多次使用,建议先编译:
compiled_pattern = re.compile(r'\d{3}-\d{3}-\d{4}') # 匹配如 123-456-7890
if compiled_pattern.match("123-456-7890"):
print("电话号码格式匹配")
编译后可重复使用,提升性能。
基本上就这些。根据你要验证的内容(数字、字母、邮箱、URL 等),构造合适的正则表达式,再选择 match、search 或 fullmatch 方法判断即可。










