re.match() 函数的返回值有三种可能:

- 匹配对象:如果字符串的开头部分与正则表达式成功匹配,返回一个
re.Match对象。 None:如果字符串的开头部分与正则表达式不匹配,返回None。- 抛出异常:如果传入的正则表达式本身有语法错误,会抛出
re.error异常。
下面我们逐一详细说明。
成功匹配:返回 re.Match 对象
当 re.match() 找到匹配项时,它会返回一个 re.Match 对象,这个对象包含了丰富的信息,你可以用它来获取匹配到的具体内容、位置等。
re.Match 对象的主要属性和方法:
| 属性/方法 | 描述 | 示例 |
|---|---|---|
group() |
返回匹配到的字符串,这是最常用的方法。 | match.group() |
groups() |
返回一个包含所有捕获组匹配结果的元组。 | match.groups() |
groupdict() |
返回一个包含所有命名捕获组的字典。 | match.groupdict() |
start() |
返回匹配的起始位置,对于 re.match(),总是 0。 |
match.start() |
end() |
返回匹配的结束位置(不包含该位置)。 | match.end() |
span() |
返回一个包含 (start, end) 的元组,对于 re.match(),总是 (0, end)。 |
match.span() |
lastindex |
最后一个匹配到的捕获组的索引,如果没有则为 None。 |
match.lastindex |
lastgroup |
最后一个匹配到的命名捕获组的名称,如果没有则为 None。 |
match.lastgroup |
代码示例
示例 1:基本匹配和 group()
import re
text = "Hello, World!"
pattern = r"Hello"
# 尝试从字符串开头匹配
match = re.match(pattern, text)
if match:
print("匹配成功!")
print(f"匹配到的字符串: {match.group()}") # 使用 group() 获取匹配内容
print(f"匹配的起始位置: {match.start()}")
print(f"匹配的结束位置: {match.end()}")
print(f"匹配的跨度: {match.span()}")
else:
print("匹配失败!")
输出:
匹配成功!
匹配到的字符串: Hello
匹配的起始位置: 0
匹配的结束位置: 5
匹配的跨度: (0, 5)
示例 2:使用捕获组 和 groups()
捕获组允许你从匹配的字符串中提取特定的部分。

import re
text = "My phone number is 123-456-7890."
pattern = r"My phone number is (\d{3})-(\d{3})-(\d{4})"
match = re.match(pattern, text)
if match:
print("匹配成功!")
print(f"整个匹配的字符串: {match.group()}") # group(0) 是整个匹配
print(f"第一个捕获组: {match.group(1)}") # group(1) 是第一个括号里的内容
print(f"第二个捕获组: {match.group(2)}")
print(f"第三个捕获组: {match.group(3)}")
# groups() 一次性获取所有捕获组
print(f"所有捕获组 (元组): {match.groups()}")
else:
print("匹配失败!")
输出:
匹配成功!
整个匹配的字符串: My phone number is 123-456-7890
第一个捕获组: 123
第二个捕获组: 456
第三个捕获组: 7890
所有捕获组 (元组): ('123', '456', '7890')
示例 3:使用命名捕获组 (?P<name>...) 和 groupdict()
命名捕获组让代码更具可读性。
import re
text = "Order #12345 is confirmed."
pattern = r"Order #(?P<order_id>\d+) is (?P<status>\w+)\."
match = re.match(pattern, text)
if match:
print("匹配成功!")
print(f"整个匹配的字符串: {match.group()}")
print(f"通过名称获取 order_id: {match.group('order_id')}")
print(f"通过名称获取 status: {match.group('status')}")
# groupdict() 一次性获取所有命名捕获组
print(f"所有命名捕获组 (字典): {match.groupdict()}")
else:
print("匹配失败!")
输出:
匹配成功!
整个匹配的字符串: Order #12345 is confirmed.
通过名称获取 order_id: 12345
通过名称获取 status: confirmed
所有命名捕获组 (字典): {'order_id': '12345', 'status': 'confirmed'}
匹配失败:返回 None
如果字符串的开头不符合正则表达式,re.match() 会返回 None。这是一个非常重要的点:re.match() 只检查字符串的开头,而不是整个字符串。

import re
text = "This is a test string."
pattern = r"Hello" # 尝试匹配以 "Hello" 开头的字符串
match = re.match(pattern, text)
if match:
print("匹配成功!")
else:
print("匹配失败!") # 因为 "This" 不等于 "Hello"
print(f"re.match 的返回值是: {match}")
输出:
匹配失败!
re.match 的返回值是: None
一个常见的错误:
如果你想检查字符串中任意位置是否存在某个模式,应该使用 re.search()。
import re
text = "This is a test string."
pattern = r"test"
# re.match() 只检查开头,会失败
match1 = re.match(pattern, text)
print(f"re.match 的结果: {match1}") # None
# re.search() 会扫描整个字符串,会成功
match2 = re.search(pattern, text)
print(f"re.search 的结果: {match2}") # <re.Match object; span=(10, 14), match='test'>
正则表达式错误:抛出 re.error 异常
如果你写的正则表达式本身有语法错误,程序会抛出异常。
import re
# 这是一个错误的正则表达式,括号没有闭合
pattern = r"Hello (world"
try:
re.match(pattern, "Hello world")
except re.error as e:
print(f"正则表达式错误: {e}")
输出:
正则表达式错误: missing ), unterminated subpattern at position 6
总结与最佳实践
| 场景 | re.match() 返回值 |
如何处理 |
|---|---|---|
| 字符串开头匹配成功 | re.Match 对象 |
使用 if match: 或 if match is not None: 来判断,然后通过 match.group() 等方法获取数据。 |
| 字符串开头匹配失败 | None |
使用 if not match: 或 if match is None: 来判断。 |
| 正则表达式语法错误 | 抛出 re.error 异常 |
使用 try...except re.error 块来捕获和处理。 |
重要提示:
re.match()只匹配开头,如果你想在字符串的任意位置查找,请使用re.search()。- 总是检查返回值,在尝试调用
match.group()之前,务必先检查match是否为None,否则会抛出AttributeError异常。
# 错误示范
match = re.match(r"Hi", "Hello, world!")
print(match.group()) # 这会抛出 AttributeError: 'NoneType' object has no attribute 'group'
# 正确示范
match = re.match(r"Hi", "Hello, world!")
if match:
print(match.group())
else:
print("没有匹配到,不能调用 group() 方法。") 