在Python中使用正则表达式

169 阅读4分钟

1. 导入 re 模块

首先,你需要导入Python的标准库中的re模块:

import re

2. 编写正则表达式模式

正则表达式是一个特殊的字符序列,它描述了字符串的某种模式或规则。例如,要匹配一个电子邮件地址,你可以编写如下正则表达式:

email_pattern = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+"

注意:在Python中,通常会在字符串前加上字母r以表示这是一个原始字符串(raw string),这样可以避免反斜杠转义问题。

3. 使用 re 模块的常用函数

查找所有匹配项 - findall()

查找字符串中所有与给定模式匹配的子串,并返回一个列表:

matches = re.findall(email_pattern, "Contact us at support@example.com or sales@company.org")
print(matches)  # Output: ['support@example.com', 'sales@company.org']

匹配开头 - match()

尝试从字符串的起始位置匹配一个模式,如果匹配成功,则返回一个匹配对象;否则返回None:

result = re.match(r"Hello", "Hello world!")
if result:
    print("Match found:", result.group())
else:
    print("No match")

搜索整个字符串 - search()

扫描整个字符串并返回第一个成功的匹配结果:

result = re.search(r"world", "Hello world!")
if result:
    print("Found:", result.group())  # Output: Found: world
else:
    print("Not found")

替换匹配项 - sub()

将匹配到的内容替换为指定的新字符串:

new_text = re.sub(r"\d+", "number", "There are 123 apples and 456 oranges.")
print(new_text)  # Output: There are number apples and number oranges.

分割字符串 - split()

按照匹配的模式分割字符串,并返回一个列表:

words = re.split(r"\W+", "Hello, how are you?")
print(words)  # Output: ['Hello', 'how', 'are', 'you', '']

4. 编译正则表达式

为了提高性能,特别是当你多次使用同一个正则表达式时,你可以先编译它:

compiled_pattern = re.compile(email_pattern)
matches = compiled_pattern.findall("Contact us at support@example.com or sales@company.org")
print(matches)  # Output: ['support@example.com', 'sales@company.org']

5. 获取更多信息 - 使用匹配对象

当你调用match()或search()时,它们会返回一个匹配对象,其中包含了有关匹配的信息。你可以从中提取更多细节:

result = re.search(r"(\w+) (\w+)", "John Doe")
if result:
    print("Full name:", result.group())        # Output: Full name: John Doe
    print("First name:", result.group(1))      # Output: First name: John
    print("Last name:", result.group(2))       # Output: Last name: Doe

6. 使用标志(Flags)

某些情况下,你可能希望改变正则表达式的行为。可以通过传递额外的标志来实现这一点。例如,使匹配不区分大小写:

case_insensitive_match = re.search("hello", "Hello World!", flags=re.IGNORECASE)
if case_insensitive_match:
    print("Case-insensitive match found!")

常见的标志包括:
re.IGNORECASE 或 re.I:忽略大小写的匹配。
re.MULTILINE 或 re.M:多行模式,改变'^''$'的行为。
re.DOTALL 或 re.S:让.匹配包括换行符在内的所有字符。

7. 正则表达式的元字符和特殊序列

了解一些常用的元字符(如^, $, ., *, +, ?, {m,n}, [], (), |)以及特殊序列(如\d, \s, \w)对于构建有效的正则表达式至关重要。这些符号赋予了正则表达式强大的灵活性和表达能力。

import re
# 编写正则表达式模式,用于匹配电子邮件地址
email_pattern = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+"

# 查找所有匹配项 - findall()
匹配结果 = re.findall(email_pattern, "请联系 support@example.com 或 sales@company.org")
print("找到的电子邮件地址:", 匹配结果)  # 输出: ['support@example.com', 'sales@company.org']

# 匹配开头 - match()
result = re.match(r"你好", "你好,世界!")
if result:
    print("匹配成功:", result.group())  # 输出: 匹配成功: 你好
else:
    print("没有匹配")

# 搜索整个字符串 - search()
result = re.search(r"世界", "你好,世界!")
if result:
    print("找到:", result.group())  # 输出: 找到: 世界
else:
    print("未找到")

# 替换匹配项 - sub()
新文本 = re.sub(r"\d+", "数字", "这里有123个苹果和456个橙子。")
print("替换后的文本:", 新文本)  # 输出: 这里有数字个苹果和数字个橙子。

# 分割字符串 - split()
words = re.split(r"\W+", "你好,你怎么样?")
print("分割后的单词列表:", words)  # 输出: ['你好', '你', '怎么样', '']

# 编译正则表达式以提高性能
compiled_pattern = re.compile(email_pattern)
匹配结果 = compiled_pattern.findall("请联系 support@example.com 或 sales@company.org")
print("找到的电子邮件地址:", 匹配结果)  # 输出: ['support@example.com', 'sales@company.org']

# 获取更多信息 - 使用匹配对象
result = re.search(r"(\w+) (\w+)", "张三 李四")
if result:
    print("全名:", result.group())        # 输出: 全名: 张三 李四
    print("名字:", result.group(1))      # 输出: 名字: 张三
    print("姓氏:", result.group(2))       # 输出: 姓氏: 李四

# 使用标志(Flags)使匹配不区分大小写
case_insensitive_match = re.search("hello", "Hello World!", flags=re.IGNORECASE)
if case_insensitive_match:
    print("不区分大小写的匹配找到了!")

注意:确保你的环境支持UTF-8编码,以便正确显示中文字符。

关于中文字符的支持

为了确保中文字符能够被正确处理和显示,请注意以下几点:

文件编码: 保存Python脚本时,请确保文件保存为UTF-8编码格式。大多数现代编辑器默认使用UTF-8,但你可以检查并更改设置以确认。

终端或命令行工具: 运行Python脚本的终端或命令行工具也应支持UTF-8编码。如果你遇到乱码问题,可能需要调整这些工具的编码设置。

Python源文件声明: 虽然对于Python 3.x来说不是必须的,但在某些情况下,在文件顶部添加如下声明可能会有所帮助:

# -*- coding: utf-8 -*-