ZetCode

Python Match.end 方法

最后修改于 2025 年 4 月 20 日

Match.end 简介

Match.end 方法是 Python re 模块的一部分。它返回正则表达式找到的匹配的结束位置。

此方法在 re.searchre.match 和其他正则表达式操作返回的匹配对象上可用。它有助于在字符串中定位匹配项。

该方法可以接受一个可选的组号参数。如果没有,它将返回整个匹配的结尾。如果指定了组号,它将返回该特定组的结尾。

基本语法

Match.end 的语法很简单

match.end([group])

可选的 group 默认为 0(整个匹配)。它必须在模式中定义的组的范围内。

Match.end 的基本用法

让我们从一个查找单词结束位置的简单示例开始。

basic_end.py
#!/usr/bin/python

import re

text = "The quick brown fox jumps over the lazy dog"
pattern = re.compile(r'fox')

match = pattern.search(text)
if match:
    print(f"Found 'fox' ending at position {match.end()}")

此示例查找单词“fox”并打印其结束位置。end 方法给出匹配项之后立即存在的索引。

match = pattern.search(text)

我们在文本中搜索我们的模式。如果成功,这将返回一个匹配对象,其中包含匹配位置信息。

print(f"Found 'fox' ending at position {match.end()}")

end 方法返回匹配结束的索引。请记住 Python 使用从 0 开始的索引。

将 Match.end 与组一起使用

我们可以获取模式中特定捕获组的结束位置。

group_end.py
#!/usr/bin/python

import re

text = "Date: 2023-12-25"
pattern = re.compile(r'Date: (\d{4})-(\d{2})-(\d{2})')

match = pattern.search(text)
if match:
    print(f"Full match ends at: {match.end()}")
    print(f"Year ends at: {match.end(1)}")
    print(f"Month ends at: {match.end(2)}")
    print(f"Day ends at: {match.end(3)}")

这展示了如何获取完整匹配项和特定组的结束位置。组 0 始终是完整匹配项。

处理可选组

处理可选组时,我们需要检查它们是否匹配。

optional_groups.py
#!/usr/bin/python

import re

text = "Color: blue"
pattern = re.compile(r'Color: (\w+)(?:, shade: (\w+))?')

match = pattern.search(text)
if match:
    print(f"Color ends at: {match.end(1)}")
    if match.group(2):
        print(f"Shade ends at: {match.end(2)}")
    else:
        print("No shade specified")

这演示了可选组的安全处理。我们在调用 end(2) 之前检查组 2 是否存在,以避免异常。

字符串切片中的 Match.end

结束位置对于提取匹配项后的文本很有用。

slicing.py
#!/usr/bin/python

import re

text = "Error: 404 - Page not found"
pattern = re.compile(r'Error: \d+ - ')

match = pattern.search(text)
if match:
    error_message = text[match.end():]
    print(f"Error message: '{error_message}'")

在这里,我们使用 end 对字符串进行切片并获取错误代码前缀之后的所有内容。这是该方法的常见用例。

使用 finditer 进行多次匹配

处理多个匹配项时,end 有助于跟踪位置。

finditer.py
#!/usr/bin/python

import re

text = "apple 123, banana 456, cherry 789"
pattern = re.compile(r'(\w+) (\d+)')

for match in pattern.finditer(text):
    print(f"Word '{match.group(1)}' ends at {match.end(1)}")
    print(f"Number '{match.group(2)}' ends at {match.end(2)}")

这会迭代所有匹配项,展示 end 如何与每个匹配项一起工作。这些位置相对于原始字符串。

Match.end 与 Match.endpos

区分 endendpos 非常重要。

end_vs_endpos.py
#!/usr/bin/python

import re

text = "Search this string"
pattern = re.compile(r'this')

match = pattern.search(text, 0, 10)  # Only search first 10 chars
if match:
    print(f"Match ends at: {match.end()}")  # Position in string
    print(f"Search ended at: {match.endpos}")  # 10 from search params

end 给出匹配项的结束位置,而 endpos 显示搜索停止的位置。它们有不同的用途。

错误处理

我们应该处理组不存在或匹配失败的情况。

error_handling.py
#!/usr/bin/python

import re

text = "No numbers here"
pattern = re.compile(r'(\d+)')

match = pattern.search(text)
if not match:
    print("No match found")
else:
    try:
        print(match.end(1))
    except IndexError:
        print("Group 1 didn't participate in match")

这展示了在处理潜在的缺失匹配项或组时如何正确处理错误。在使用 end 之前,始终检查是否存在匹配项。

最佳实践

使用 Match.end 时,请遵循以下最佳实践

性能注意事项

end 方法非常高效,因为它只是从匹配对象返回一个预先计算的值。使用它没有性能损失。

但是,在同一匹配项上重复调用它是不必要的,因为该值不会改变。如果需要多次使用它,请将其存储在变量中。

来源

Python Match.end() 文档

本教程涵盖了 Python Match.end 方法的基本方面。掌握匹配位置将帮助您更有效地使用 Python 中的正则表达式。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。我在编程教学方面拥有超过十年的经验。

列出所有 Python 教程