"""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()
本例需在 Windows CPython 3.12 and fixed in-memory Unicode, ASCII, bytes, text and regex fixtures 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPython 3.12 and fixed in-memory Unicode, ASCII, bytes, text and regex fixtures
入口文件:projects/python-lab/python-re.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python-re.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPython 3.12 and fixed in-memory Unicode, ASCII, bytes, text and regex fixtures。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a299.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip