regex

Parsing

高级正则表达式引擎

概述 regex

regex 模块是 Python 内置 re 模块的直接替代品,提供附加功能,包括模糊匹配(近似字符串匹配)、可变宽度后向查找、具有重复捕获的命名捕获组、POSIX 字符类和原子分组。

正则表达式可通过 micropip 在PyRun中使用。当您需要匹配具有轻微拼写错误的模式(模糊匹配)、处理复杂的 Unicode 文本或使用标准 re 模块不支持的正则表达式功能时,它特别有用。

代码和执行输出

命名捕获组和模糊模式匹配。

Regex: Named Groups & Fuzzy在编辑器中运行
import regex

# Named capture groups — parse a log line
log = "2025-07-04 14:32:01 ERROR [auth] Login failed for user@example.com"
pattern = r"(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2}) (?P<level>\w+) \[(?P<module>\w+)\] (?P<message>.+)"
m = regex.match(pattern, log)
if m:
    for k, v in m.groupdict().items():
        print(f"  {k:<10}: {v}")

# Fuzzy matching — find 'colour' with up to 1 error
print("\nFuzzy search (≤1 substitution):")
text = "I prefer colour and cilor and colouur"
for hit in regex.finditer(r"(?:colour){s<=1}", text):
    print(f"  found '{hit.group()}' at {hit.span()}")

相关套餐

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。