蓝色天空.知识 · 实践 · 创造
我的收藏
Python 教程目录 82章
课程介绍
Python / LEARN BY DOING

Python re:匹配范围、分组与文本处理

用工单标签、联系地址和日志字段区分匹配、查找、分割和替换,并核对每个结果。

学完这一章,你能够

  • 用工单标签、联系地址和日志字段区分匹配、查找、分割和替换,并核对每个结果。

选择匹配范围,再读取结果

导入 re 后,优先用原始字符串写带反斜杠的模式,例如 r"\d+"。Python 字符串与正则语法各自解释反斜杠。模式和输入都应为 str,或都为 bytes。正则适合有明确规则的片段,提取网页链接时应先用 HTML 解析器读取属性。

match 检查输入起点,search 找任意位置的第一个匹配,fullmatch 要求覆盖整个输入。返回 Match 或 None。需要验证完整标签时直接用 fullmatch,因为 $ 也能在末尾换行之前匹配。

findall 按从左到右的顺序收集不重叠的结果,包括零宽匹配。无捕获组时返回完整匹配,一个捕获组时返回该组,多个组时返回元组。finditer 逐个产生 Match,可读取文本及左闭右开的索引。

重复使用同一规则时用 compile 保存 Pattern,也可指定 pos 和 endpos 在原字符串的指定范围工作。模块级函数会缓存近期模式,purge 清空该缓存。实际耗时还受模式与输入影响。

读字符、边界、量词与分组

普通字母按字面匹配,带语法含义的字面输入用 re.escape 放进模式,例如文件名中的 . 和 +。点号默认只排除换行符 \n,DOTALL 时也匹配换行。字符集 [AEIOUaeiou] 从列出的字符中选一个。

对 str,\d 匹配 Unicode 十进制数字,\w 匹配 Unicode 字母数字及下划线,\s 匹配 Unicode 空白。\D、\W、\S 分别匹配对应集合的补集。ASCII 标志把正向集合限制为 ASCII,补集随之变化。

^ 通常检查起点,$ 检查结尾或末尾换行之前。MULTILINE 让这两个锚点也在行边界匹配,match 的起点要求仍然存在。

*、+、? 依次表示零次或多次、一次或多次、零次或一次,{m,n} 含两个端点。它们默认先尝试较长结果,追加 ? 时先尝试较短结果。| 按顺序尝试分支。括号可让量词作用于整个片段,(?:...) 分组但不捕获。

group() 或 group(0) 取完整匹配,group(n) 或 group(name) 取捕获。groups(default=...) 读取所有编号组,未参与匹配的组默认是 None。start、end 和 span 可按组查询位置,未参与时给出 -1 或 (-1, -1)。

用标志表达匹配条件

IGNORECASE 忽略大小写。MULTILINE 改变 ^ 和 $,DOTALL 改变点号,ASCII 改变 str 的字符类别。可用 | 合并标志。实验以 Unicode 数字和字母比较默认与 ASCII 两种结果。

VERBOSE 可把长模式分行并加入注释。普通空白会被忽略,字符集内的空格及转义空格仍有意义。用 (?P<name>...) 命名分组,groupdict() 可提取结构化字段。实验解析虚构的角色、服务、主机标签。

输入很长或来自外部时,要同时测成功和接近成功的失败输入。本站用 fullmatch 测 (a+)+b、a+b、(?>a+)b 和 a++b。对连续的 a 加错误结尾,嵌套量词在本机随重复数从 12 增至 22 耗时明显上升。其余三种写法也用 100000 个 a 验证了成功和失败。四种写法在生成的短输入中接受结果一致,嵌套写法仍多一个捕获组。Python 3.11 起支持原子组和占有量词。原子组可能改变匹配,例如 a+a 能匹配 aa,而 (?>a+)a 失败。重写前要核对完整匹配、捕获和失败路径。解压章节 ZIP 后运行 python re-lab/re_backtracking.py 可复测。脚本限制嵌套模式的输入长度,并给每个测量进程设置超时。

替换、分割和联系字段练习

sub 的替换项可以是字符串模板或接收 Match 的函数。count 控制最多替换多少次,0 表示不限。subn 返回新字符串和替换次数。用命名组与 \g<name> 可明确重排日期字段,日期是否存在还需由 datetime 检查。

split 按分隔模式拆分文本,捕获组会保留分隔符。maxsplit 限制拆分次数。分隔符出现在开头或末尾时可能产生空字段,允许空匹配的模式也可能参与分割。先根据数据样例确认这些结果再决定如何处理。

联系练习用 fullmatch 检查本站约定的 ASCII 邮箱形状,用 finditer 从短记录中提取地址。模式只覆盖常见标签,域名和邮箱能否投递需要额外验证。电话号码例子只提取形如三位、三位、四位且带连字符的 ASCII 字段,并检查更长数字串中的误匹配。

下载并重跑边界用例

解压后运行 python python-re.py。依次核对编译、匹配位置、捕获、替换、联系字段和短输入回溯。修改一个字母、分隔符或换行,再比较输出里的预期与实际。

下载本章实验包 (mbskycom202611a463.zip) ↓ 查看运行说明 ↗

核心函数

成员、方法或符号作用和条件
re.compile(pattern, flags=0)构造可复用的 Pattern,方法可按输入范围工作。
re.search(pattern, string, flags=0)找第一个匹配,失败返回 None。
re.match(pattern, string, flags=0)只尝试从字符串起点匹配,允许留下后缀。
re.fullmatch(pattern, string, flags=0)要求完整字符串符合模式,失败返回 None。
re.findall(pattern, string, flags=0)返回不重叠结果的列表,捕获组个数决定元素形状。
re.finditer(pattern, string, flags=0)按顺序迭代不重叠的 Match,可读取位置及分组。
re.sub(pattern, repl, string, count=0, flags=0)替换左起不重叠匹配,repl 可为模板或函数。
re.split(pattern, string, maxsplit=0, flags=0)按匹配分隔,捕获的分隔符会保留。
re.escape(pattern)转义模式中的特殊字符,用于匹配字面文本。
re.purge()清除模块的正则缓存,手上持有的 Pattern 仍可使用。

匹配对象

成员、方法或符号作用和条件
Match.group()返回整个匹配的文本,与 group(0) 一致。
Match.group(n)获取编号或命名组,可一次查询多个组。
Match.groups(default=None)按编号返回所有捕获组,未参与的组使用 default。
Match.start(group=0) / Match.end(group=0)取得起点与不包含的终点,未参与组返回 -1。
Match.span(group=0)返回索引对 (start, end)。

常用元字符

成员、方法或符号作用和条件
.默认匹配除 \n 外的一个字符。
\dstr 模式匹配 Unicode 十进制数字,ASCII 时只包括 0 到 9。
\D\d 的补集,受同一标志影响。
\w匹配 Unicode 字母数字及下划线,ASCII 时限于对应 ASCII 字符。
\W\w 的补集。
\s匹配空格、制表符等 Unicode 空白,ASCII 时使用 ASCII 空白集合。
\S\s 的补集。
[...]从字符集选一个字符,范围表达一段连续码位。
^匹配字符串开头,MULTILINE 也匹配换行后。
$匹配字符串结尾或最后的换行之前,MULTILINE 也匹配内部换行之前。
*前一原子重复零次或多次。
+前一原子至少重复一次。
?前一原子可选,默认优先尝试一次。
{m,n}前一原子重复 m 至 n 次,默认优先尝试较多次数。
|按顺序尝试各个备选分支。
(...)捕获子表达式,也可把多个原子作为整体重复。

编译标志

成员、方法或符号作用和条件
re.IGNORECASE / re.I按忽略大小写的规则匹配。
re.MULTILINE / re.M让 ^ 和 $ 同时识别行边界。
re.DOTALL / re.S让点号也能匹配 \n。
re.ASCII / re.Astr 模式中的字词、数字、空白和边界按 ASCII 判断。
re.VERBOSE / re.X忽略一般空白及行尾注释,保留有语法意义的空格。

本章自编源码与运行范围

含完整源码 · 168 行
展开查看收起
Python
"""Run the lesson against fixed, synthetic inputs."""
from datetime import date
import json
import re


def main():
    checks = []

    def check(name, actual, expected, inputs, operation):
        if actual != expected:
            raise AssertionError((name, actual, expected))
        checks.append(dict(name=name, inputs=inputs, operation=operation, actual=actual,
                           expected=expected, passed=True))

    def rejects(name, error, operation, inputs):
        try:
            operation()
        except error as raised:
            check(name, type(raised).__name__, error.__name__, inputs, 'Execute the operation and capture its error')
        else:
            raise AssertionError(name)

    text = 'ticket-42 and 65'
    number = re.compile(r'[0-9]+')
    check('compiled range and reuse', [number.match(text, 7, 8).group(), number.findall(text, 7, 13),
                                      number.findall('job-38')], ['4', ['42'], ['38']], [text, 'job-38'],
          'Match and find all within explicit bounds, then reuse the pattern')
    check('search first span or none', [re.search(r'[0-9]+', text).span(), re.search('idle', text) is None],
          [(7, 9), True], text, 'Search for the first number, then an absent token')
    check('match checks start', [re.match('ticket', text).group(), re.match('42', text) is None],
          ['ticket', True], text, 'Match a prefix and test that an interior token fails')
    labels = ['T-40', 'T-40extra', 'T-40\n']
    check('fullmatch rejects suffix and newline', [bool(re.fullmatch(r'T-[0-9]+', x)) for x in labels],
          [True, False, False], labels, 'Compare valid label, suffix and terminal newline')
    fields = 'cpu=14 ram=6'
    check('findall forms and empty matches',
          [re.findall(r'\d+', fields), re.findall(r'\w+=(\d+)', fields), re.findall(r'(\w+)=(\d+)', fields),
           re.findall(r'\d*', 'x2'), re.findall(r'\d+', 'none')],
          [['14', '6'], ['14', '6'], [('cpu', '14'), ('ram', '6')], ['', '2', ''], []],
          [fields, 'x2', 'none'], 'Use zero, one and two captures and a pattern admitting empty matches')
    check('finditer values and spans', [(m.group(), m.span()) for m in number.finditer(text)],
          [('42', (7, 9)), ('65', (14, 16))], text, 'Iterate and recover each half-open range')
    check('sub string count and function',
          [re.sub(r'\d+', 'X', fields, count=1),
           re.sub(r'\d+', lambda m: str(int(m.group()) * 2), fields)],
          ['cpu=X ram=6', 'cpu=28 ram=12'], fields, 'Replace once with text and replace all using a callback')
    check('subn counts replacements', re.subn(r'\d+', '#', fields), ('cpu=# ram=#', 2), fields,
          'Return the transformed text with its replacement count')
    check('split limits captures and empty fields',
          [re.split(r'[0-9]+', 'red2blue31green'), re.split(r'([0-9]+)', '2red3'), re.split(r'\d+', 'red2blue3green', 1),
           re.split(r'x*', 'ab')],
          [['red', 'blue', 'green'], ['', '2', 'red', '3', ''], ['red', 'blue3green'], ['', 'a', 'b', '']],
          ['red2blue31green', '2red3', 'red2blue3green', 'ab'], 'Split and inspect retained delimiters and empty parts')
    literal_path = r'D:\drafts\brief+1.txt'
    check('escape quotes a literal path',
          [bool(re.fullmatch(re.escape(literal_path), literal_path)),
           bool(re.fullmatch(re.escape(literal_path), literal_path.replace('.', '-')))],
          [True, False], literal_path, 'Escape the path before building a full-match pattern')
    same_pattern = re.compile(r'CACHE-[0-9]{2}')
    was_cached = same_pattern is re.compile(r'CACHE-[0-9]{2}')
    re.purge()
    new_pattern = re.compile(r'CACHE-[0-9]{2}')
    check('purge clears compiled pattern cache',
          [was_cached, same_pattern is new_pattern, bool(same_pattern.fullmatch('CACHE-27'))],
          [True, False, True], 'CACHE-[0-9]{2}', 'Compare observed CPython objects before and after purge')
    m = re.fullmatch(r'(?P<kind>[A-Z]+)-([0-9]+)', 'TASK-38')
    check('match group whole and numbered', [m.group(), m.group(0), m.group('kind'), m.group(1, 2), m.span(2)],
          ['TASK-38', 'TASK-38', 'TASK', ('TASK', '38'), (5, 7)], 'TASK-38', 'Read group zero, names and indexes')
    optional = re.fullmatch(r'([A-Z]+)(?:-([0-9]+))?', 'TASK')
    check('groups defaults and unmatched span',
          [optional.groups(), optional.groups('-'), optional.start(2), optional.end(2), optional.span(2)],
          [('TASK', None), ('TASK', '-'), -1, -1, (-1, -1)], 'TASK', 'Read an optional non-participating capture')
    check('dot excludes LF by default', re.findall(r'.', 'A\r\nB'), ['A', '\r', 'B'], 'A CR LF B',
          'Check both CR and LF separately')
    digits = '4٣²A'
    check('decimal and nondecimal classes',
          [re.findall(r'\d', digits), re.findall(r'\D', digits),
           re.findall(r'\d', digits, re.A), re.findall(r'\D', digits, re.A)],
          [['4', '٣'], ['²', 'A'], ['4'], ['٣', '²', 'A']], digits, 'Compare default and ASCII decimal classes')
    words = '海_4!'
    check('word and nonword classes',
          [re.findall(r'\w', words), re.findall(r'\W', words), re.findall(r'\w', words, re.A)],
          [['海', '_', '4'], ['!'], ['_']], words, 'Compare word and complementary sets')
    spaces = 'A\t\u00a0B'
    check('space and nonspace classes',
          [re.findall(r'\s', spaces), re.findall(r'\S', spaces), re.findall(r'\s', spaces, re.A)],
          [['\t', '\u00a0'], ['A', 'B'], ['\t']], spaces, 'Check Unicode nonbreaking space and ASCII space category')
    check('character class and literal match',
          [re.findall('[AEIOUaeiou]', 'Map Blue'), re.search('blue', 'map blue').span()],
          [['a', 'u', 'e'], (4, 8)], ['Map Blue', 'map blue'], 'Extract vowels from a set and search a literal')
    lines = '7 top\n8 lower\n'
    check('caret and multiline anchors',
          [re.findall(r'^\d', lines), re.findall(r'^\d', lines, re.M),
           re.match(r'^8', lines, re.M) is None],
          [['7'], ['7', '8'], True], lines, 'Compare ordinary and multiline caret, including match start')
    check('dollar and multiline anchors',
          [re.search('lower$', lines).span(), re.findall(r'\w+$', lines, re.M)],
          [(8, 13), ['top', 'lower']], lines, 'Match before terminal newline and before each line break')
    quantifiers = ['x*', 'x+', 'x?', 'x{2,3}', 'x??', 'x{2,3}?']
    check('greedy and lazy quantifiers',
          [[re.match(rule, 'xxxx').group() for rule in quantifiers],
           [re.match(rule, 'q') is not None for rule in quantifiers[:4]]],
          [['xxxx', 'xxxx', 'x', 'xxx', '', 'xx'], [True, False, True, False]], quantifiers,
          'Compare greedy and lazy bounds and repeat counts at zero')
    check('alternatives are tried left to right', re.match(r'job|jobs', 'jobs').group(), 'job', 'jobs',
          'Compare ordered alternatives that share a prefix')
    grouped = re.fullmatch(r'(go)+', 'gogogo')
    check('capturing repeated group', [grouped.group(), grouped.group(1), re.fullmatch(r'(?:go)+', 'gogo').groups()],
          ['gogogo', 'go', ()], ['gogogo', 'gogo'], 'Repeat a group and compare its last capture with non-capturing syntax')
    check('ignore case and combined flags',
          [bool(re.fullmatch('task', 'TASK', re.I)), re.findall(r'^job', 'run\nJOB', re.I | re.M)],
          [True, ['JOB']], ['TASK', 'run\nJOB'], 'Apply case-insensitivity alone and with multiline')
    check('dotall includes LF', re.fullmatch(r'A.B', 'A\nB', re.S).group(), 'A\nB', 'A\nB',
          'Match a newline when DOTALL is set')
    check('ASCII flag changes categories and boundary',
          [bool(re.fullmatch(r'\w+', '海')), bool(re.fullmatch(r'\w+', '海', re.A)),
           bool(re.search(r'\b[A-Z]', '海T')), bool(re.search(r'\b[A-Z]', '海T', re.A))],
          [True, False, False, True], ['海', '海T'], 'Observe word category and boundary changes')
    labels = re.compile(r'''
        (?P<role>[a-z]+)     :  # role label
        (?P<service>[a-z]+)  @  # service label
        (?P<host>[a-z]+[.]example)
    ''', re.X)
    check('verbose labels and literal space',
          [labels.fullmatch('reader:feed@lab.example').groupdict(), bool(re.fullmatch(r'a[ ]b', 'a b', re.X)),
           bool(re.fullmatch(r'a\ b', 'a b', re.X)), labels.fullmatch('reader:feed@lab|example') is None],
          [dict(role='reader', service='feed', host='lab.example'), True, True, True], 'reader:feed@lab.example',
          'Extract named fixture fields and verify both literal-space forms')
    local = r'[A-Za-z0-9_+-]+(?:[.][A-Za-z0-9_+-]+)*'
    domain = r'[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*'
    email = local + '@' + domain + r'(?:[.]' + domain + r')*[.][A-Za-z]{2,}'
    addresses = ['ops+lab@desk.example', 'bad..tag@desk.example', 'no@-desk.example', 'ops@desk|example',
                 'ops@desk.example\n', '用户@desk.example']
    check('limited email shape accepts and rejects', [bool(re.fullmatch(email, x)) for x in addresses],
          [True, False, False, False, False, False], addresses, 'Validate full ASCII address shapes for this exercise')
    contacts = 'Mail <ops+lab@desk.example>, <night@desk.example>; skip <bad@desk|example>.'
    check('extract contact addresses', [m.group(1) for m in re.finditer('<(' + email + ')>', contacts)],
          ['ops+lab@desk.example', 'night@desk.example'], contacts, 'Extract only well-formed bracketed contacts')
    phones = 'Try 608-555-0143 or 415-555-0178, skip 1608-555-0143 and 415-555-0178-2.'
    check('extract bounded ASCII telephone fields',
          re.findall(r'(?<![0-9-])[0-9]{3}-[0-9]{3}-[0-9]{4}(?![0-9-])', phones),
          ['608-555-0143', '415-555-0178'], phones, 'Collect phone-shaped fields outside longer number or hyphen runs')
    pattern = r'(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/(?P<year>[0-9]{4})'
    rearranged = re.sub(pattern, r'\g<year>-\g<month>-\g<day>', 'logged 02/29/2024 and 02/30/2024')
    check('rearrange named date fields', rearranged, 'logged 2024-02-29 and 2024-02-30', '02/29/2024 and 02/30/2024',
          'Reorder both shape-matching dates with a replacement template')
    rejects('regex date shape is not calendar validity', ValueError, lambda: date.fromisoformat(rearranged[-10:]),
            '2024-02-30 after replacement')
    check('raw string leaves escape to regex', [len(r'\d'), bool(re.fullmatch(r'\d', '7')), bool(re.fullmatch(r'\t', '\t'))],
          [2, True, True], [r'\d', r'\t'], 'Compare pattern length with matches of a digit and a tab')
    rejects('str and bytes cannot mix', TypeError, lambda: re.search(rb'\d', '7'), 'bytes pattern and str input')
    segments = '<left><right>'
    check('dot greedy versus lazy', [re.search(r'<.*>', segments).group(), re.search(r'<.*?>', segments).group()],
          [segments, '<left>'], segments, 'Search first with greedy dot, then with lazy dot')
    short = 'a' * 10 + '!'
    check('bounded backtracking fixture and simpler pattern',
          [[bool(re.fullmatch(p, x)) for x in ('aaa', short)] for p in (r'(a+)+', r'a+')],
          [[True, False], [True, False]], ['aaa', short], 'Test two patterns against short positive and failing fixtures')
    check('atomic groups can change the language',
          [bool(re.fullmatch(r'(a*)a', 'aa')), bool(re.fullmatch(r'(?>a*)a', 'aa'))], [True, False],
          'aa', 'Prevent backtracking into a greedy group and compare outcomes')
    print(json.dumps(checks, ensure_ascii=False))


if __name__ == '__main__':
    main()

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

本章附件与实例包

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a299.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip

常见错误与边界检查

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

技术规范与官方资料

练习与参考解答

查看参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习