当前位置:首页 > Python > 正文

Python正则表达式检验字符串完全指南 | Python正则教程

Python正则表达式检验字符串完全指南

掌握re模块核心方法,轻松验证各种字符串模式

正则表达式基础

正则表达式(Regular Expression)是处理字符串的强大工具,用于匹配、查找、替换和验证文本。Python通过内置的re模块提供正则表达式支持。

导入re模块

使用正则表达式前需要导入Python的re模块:

import re

常用正则表达式元字符

字符 描述 示例
. 匹配任意字符(除换行符) a.c 匹配 "abc", "aac"
^ 匹配字符串开头 ^abc 匹配 "abc"开头
$ 匹配字符串结尾 xyz$ 匹配以"xyz"结尾
* 匹配0次或多次 ab*c 匹配 "ac", "abc", "abbc"
+ 匹配1次或多次 ab+c 匹配 "abc", "abbc"
? 匹配0次或1次 ab?c 匹配 "ac", "abc"
{m} 匹配m次 a{3} 匹配 "aaa"
{m,n} 匹配m到n次 a{2,4} 匹配 "aa", "aaa", "aaaa"
[...] 匹配字符集合 [abc] 匹配 "a", "b"或"c"
\d 匹配数字(0-9) \d+ 匹配一个或多个数字
\w 匹配字母数字下划线 \w{4} 匹配4位字母数字
\s 匹配空白字符 \s+ 匹配一个或多个空白

Python re模块核心方法

1. re.match() - 检查字符串开头

从字符串起始位置匹配模式,成功返回匹配对象,失败返回None。

import re

pattern = r"hello"
text = "hello world"

result = re.match(pattern, text)
if result:
    print("匹配成功:", result.group())
else:
    print("匹配失败")
# 输出: 匹配成功: hello

2. re.search() - 搜索整个字符串

扫描整个字符串,返回第一个成功的匹配。

text = "Python is powerful. Python is easy."
pattern = r"Python"

result = re.search(pattern, text)
if result:
    print("找到匹配:", result.group(), "位置:", result.start())
# 输出: 找到匹配: Python 位置: 0

3. re.fullmatch() - 精确匹配整个字符串

要求整个字符串完全匹配模式,常用于验证。

# 验证手机号格式
pattern = r"1[3-9]\d{9}"
phone = "13800138000"

if re.fullmatch(pattern, phone):
    print("有效的手机号码")
else:
    print("无效的手机号码")
# 输出: 有效的手机号码

4. re.findall() - 查找所有匹配

返回字符串中所有匹配的子串列表。

text = "Apple: $1.99, Banana: $0.59, Orange: $2.49"
pattern = r"\$\d+\.\d{2}"

prices = re.findall(pattern, text)
print(prices)  # 输出: ['$1.99', '$0.59', '$2.49']

5. re.finditer() - 返回匹配迭代器

返回包含所有匹配对象的迭代器,可获取更多匹配信息。

text = "2023-05-01, 2024-01-15, 2022-12-25"
pattern = r"(\d{4})-(\d{2})-(\d{2})"

for match in re.finditer(pattern, text):
    print(f"完整日期: {match.group(0)}, 年: {match.group(1)}, 月: {match.group(2)}, 日: {match.group(3)}")
# 输出:
# 完整日期: 2023-05-01, 年: 2023, 月: 05, 日: 01
# 完整日期: 2024-01-15, 年: 2024, 月: 01, 日: 15
# 完整日期: 2022-12-25, 年: 2022, 月: 12, 日: 25

常见验证场景示例

邮箱验证

def validate_email(email):
    pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
    return re.match(pattern, email) is not None

print(validate_email("user@example.com"))  # True
print(validate_email("invalid.email@"))     # False

URL验证

def validate_url(url):
    pattern = r"^(https?://)?(www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,}(/\S*)?$"
    return re.match(pattern, url) is not None

print(validate_url("https://www.example.com"))  # True
print(validate_url("example.com/path"))         # True
print(validate_url("invalid_url"))              # False

密码强度验证

def validate_password(password):
    # 至少8个字符,包含大小写字母、数字和特殊字符
    pattern = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
    return re.match(pattern, password) is not None

print(validate_password("StrongP@ss1"))  # True
print(validate_password("weakpass"))      # False

身份证号验证

def validate_id_card(id_card):
    pattern = r"^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$"
    return re.match(pattern, id_card) is not None

print(validate_id_card("11010519900307213X"))  # True
print(validate_id_card("123456789012345"))      # False

正则表达式最佳实践

  • 使用原始字符串(raw string):在模式前加r前缀,如r"\d+"
  • 预编译常用模式:compiled_pattern = re.compile(r"pattern")
  • 添加注释:使用(?#注释)或re.VERBOSE标志
  • 测试正则表达式:使用在线工具如regex101.com验证
  • 考虑性能:避免嵌套量词和过度回溯

本教程涵盖了Python中使用正则表达式检验字符串的核心知识。通过不断练习和实际应用,您将能够轻松应对各种字符串验证需求。

发表评论