Python re 匹配多个结果

引言

在使用Python进行文本处理的过程中,经常会遇到需要从字符串中匹配多个结果的情况。Python的re模块提供了强大的正则表达式功能,可以方便地实现字符串的匹配、查找和替换等操作。本文将介绍如何使用re模块匹配多个结果,并提供代码示例进行解释。

正则表达式

正则表达式是一种用于描述、匹配和处理文本的强大工具。它使用特定的语法来定义一种模式,然后通过与待匹配的字符串进行比较,从中提取符合模式的部分。在Python中,我们可以使用re模块来实现正则表达式的功能。

re模块的基本用法

在使用re模块之前,我们需要先导入它:

import re

re模块提供了多个函数来执行正则表达式的操作,其中最常用的是re.search()re.findall()函数。

re.search()

re.search(pattern, string)函数用于在字符串中查找匹配的子串。它会从字符串的开头开始搜索,只返回第一个匹配的结果。如果找到匹配的子串,则返回一个匹配对象;否则返回None。

下面是一个使用re.search()函数的例子:

import re

string = "Hello, World!"
pattern = r"Hello"

match = re.search(pattern, string)

if match:
    print("Match found:", match.group())
else:
    print("No match found.")

运行上述代码,输出结果为:

Match found: Hello

re.findall()

re.findall(pattern, string)函数用于在字符串中查找所有匹配的子串。它会返回一个列表,其中包含所有匹配的结果。

下面是一个使用re.findall()函数的例子:

import re

string = "one, two, three, four"
pattern = r"\w+"

matches = re.findall(pattern, string)

if matches:
    print("Matches found:", matches)
else:
    print("No matches found.")

运行上述代码,输出结果为:

Matches found: ['one', 'two', 'three', 'four']

匹配多个结果的正则表达式示例

现在,我们将介绍一些常见的需要匹配多个结果的正则表达式示例。

匹配邮箱地址

邮箱地址的格式通常为username@example.com,其中username是由字母、数字和下划线组成的字符串。我们可以使用以下正则表达式来匹配邮箱地址:

import re

string = "My email address is john@example.com and my friend's email address is jane@example.com."

pattern = r"\b\w+@\w+\.\w+\b"

matches = re.findall(pattern, string)

if matches:
    print("Email addresses found:", matches)
else:
    print("No email addresses found.")

运行上述代码,输出结果为:

Email addresses found: ['john@example.com', 'jane@example.com']

匹配URL

URL的格式通常为`

import re

string = "Visit my website at  for more information."

pattern = r"https?://\w+\.\w+"

matches = re.findall(pattern, string)

if matches:
    print("URLs found:", matches)
else:
    print("No URLs found.")

运行上述代码,输出结果为:

URLs found: ['

匹配日期

日期的格式通常为YYYY-MM-DD,其中YYYY表示四位数的年份,MM表示两位数的月份,DD表示两位数的日期。我们可以使用以下正则表达式来匹配日期:

import re

string = "Today is 2022-01-01 and tomorrow is 2022-01-02."

pattern = r"\d{4}-\d{2}-\d{2}"

matches = re.findall(pattern, string)

if matches:
    print("Dates found:", matches)
else:
    print("No dates found.")

运行上述代码,输出结果为:

Dates found: ['2022-01-01', '2022-01-02']