蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHON本地 Python 环境python3-reg-expressions.py
python3-reg-expressions.py158 行
"""蓝色天空网 mbsky.com | Python re with short, local text fixtures."""
import locale
from pathlib import Path
import re
import sys

sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks


def span(match):
    return match.span() if match is not None else None


def doubled(match):
    return str(2 * int(match['amount']))


def fields_without_gaps(pattern, text):
    position = 0
    fields = []
    while position < len(text):
        match = pattern.match(text, position)
        if match is None:
            break
        fields.append(match[1])
        position = match.end()
    return fields, position


checks = Checks()
eq = checks.eq
record = 'INFO port=8080 state=ready'
eq('prefix match', span(re.match('INFO', record)), (0, 4))
eq('later token fails match', re.match('port', record), None)
eq('search at prefix', span(re.search('INFO', record)), (0, 4))
eq('search later', span(re.search('port', record)), (5, 9))
eq('search first only', span(re.search('port', 'port port')), (0, 4))
eq('search missing', re.search('queue', record), None)
eq('fullmatch rejects suffix', re.fullmatch('INFO', record), None)
eq('empty match is success', span(re.match(r'\d*', record)), (0, 0))
eq('multiline match still starts at zero', re.match('^port', 'INFO\nport', re.M), None)
eq('multiline search finds next line', span(re.search('^port', 'INFO\nport', re.M)), (5, 9))

line = 'queue SET blue green done'
lazy = r'(.*) set (.*?) .*'
greedy = r'(.*) set (.*) .*'
eq('lazy match groups', re.match(lazy, line, re.M | re.I).groups(), ('queue', 'blue'))
eq('lazy search captures', re.search(lazy, line, re.M | re.I).group(0, 1, 2), (line, 'queue', 'blue'))
eq('greedy takes longer', re.match(greedy, line, re.I)[2], 'blue green')
eq('case flag required', re.match(lazy, line), None)

digits = re.compile(r'\d+')
eq('compiled pattern type', type(digits).__name__, 'Pattern')
eq('compiled prefix misses', digits.match(record), None)
eq('pos at nondigit fails', digits.match(record, 9, 14), None)
number = digits.match(record, 10, 13)
eq('compiled match type', type(number).__name__, 'Match')
eq('endpos truncates', number.group(), '808')
eq('positions absolute', (number.start(), number.end(), number.span()), (10, 13, (10, 13)))
eq('position does not reset start anchor', re.compile(r'^port').match(record, 5), None)

match = re.compile(r'(?P<kind>[a-z]+) (?P<field>[a-z]+)(?:=(\d+))?', re.I).match('INFO port pending')
eq('whole captured string', match.group(0), 'INFO port')
eq('named and indexed groups', match.group('kind', 2), ('INFO', 'port'))
eq('first two spans', (match.span(1), match.span('field')), ((0, 4), (5, 9)))
eq('groups default', match.groups('-'), ('INFO', 'port', '-'))
eq('absent group value', match.group(3), None)
eq('absent group coordinates', (match.start(3), match.end(3), match.span(3)), (-1, -1, (-1, -1)))
checks.raises('unknown capture', IndexError, lambda: match.group(4))

label = '07-42 # ticket 903'
cleaned = re.sub(r'#.*$', '', label)
eq('strip comment', cleaned, '07-42 ')
eq('strip nondigits after comment', re.sub(r'\D', '', cleaned), '0742')
eq('wrong order leaks comment digits', re.sub(r'\D', '', label), '0742903')
eq('callback doubles all', re.sub(r'(?P<amount>\d+)', doubled, 'q15/r3/q108'), 'q30/r6/q216')
eq('count and flag replacement', re.sub('q', 'Q!', 'q15/Q3', count=1, flags=re.I), 'Q!15/Q3')
eq('replacement template', re.sub(r'(?P<key>\w+)=(?P<value>\d+)', r'\g<value>[\g<key>]', 'port=8080'), '8080[port]')
eq('subn includes count', re.subn(r'\d+', 'X', 'q15/r3'), ('qX/rX', 2))

eq('module findall zero groups', re.findall(r'\d+', 'q15/r3/q108'), ['15', '3', '108'])
eq('compiled findall', digits.findall('q15/r3/q108'), ['15', '3', '108'])
eq('findall window truncates', digits.findall('x93y478', 0, 6), ['93', '47'])
eq('findall one group', re.findall(r'([a-z])=\d+', 'x=9 y=11'), ['x', 'y'])
eq('findall two groups', re.findall(r'([a-z])=(\d+)', 'x=9 y=11'), [('x', '9'), ('y', '11')])
eq('findall misses', digits.findall('pending'), [])
iterator = re.finditer(r'\d+', '9x23y845')
eq('iterator records coordinates', [(m.group(), m.span()) for m in iterator], [('9', (0, 1)), ('23', (2, 4)), ('845', (5, 8))])
eq('iterator exhausts', list(iterator), [])
eq('iterator empty matches', [m.span() for m in re.finditer(r'a*', 'x')], [(0, 0), (1, 1)])

eq('split removes delimiters', re.split(r'\W+', 'ping; check!'), ['ping', 'check', ''])
eq('split captures delimiters and ends', re.split(r'(\W+)', ' ping; check!'), ['', ' ', 'ping', '; ', 'check', '!', ''])
eq('split one delimiter', re.split(r'\W+', ' ping; check!', maxsplit=1), ['', 'ping; check!'])
eq('split empty matches', re.split(r'a*', 'xy'), ['', 'x', 'y', ''])
eq('split really absent', re.split(r'a+', 'xy'), ['xy'])
eq('split flags', re.split('x', 'aXb', flags=re.I), ['a', 'b'])

eq('ignore case', re.compile('port', re.I).match('PORT=2').group(), 'PORT')
eq('ignore case Unicode range', bool(re.fullmatch('[a-z]', 'K', re.I)), True)
eq('multiline lines', re.findall(r'^\d+$', '8\n15\n20', re.M), ['8', '15', '20'])
eq('dot skips LF', re.fullmatch('a.b', 'a\nb'), None)
eq('dot accepts CR', bool(re.fullmatch('a.b', 'a\rb')), True)
eq('dotall includes LF', bool(re.fullmatch('a.b', 'a\nb', re.S)), True)
eq('Unicode positive classes', [bool(re.fullmatch(p, s)) for p, s in [(r'\w', '汉'), (r'\d', '3'), (r'\s', '\u00a0')]], [True, True, True])
eq('ASCII flips class membership', [bool(re.fullmatch(p, '3', re.A)) for p in (r'\d', r'\D', r'\w', r'\W')], [False, True, False, True])
eq('digit excludes superscript', re.fullmatch(r'\d', '²'), None)
eq('whitespace includes vertical tab', bool(re.fullmatch(r'\s', '\v')), True)
eq('verbose uses comments and class', bool(re.fullmatch(r'\d+ [ #] [a-z]+  # suffix', '12#ok', re.X)), True)
eq('verbose with escaped space', bool(re.fullmatch(r'x\ y', 'x y', re.X)), True)
checks.raises('locale forbids str', ValueError, lambda: re.compile(r'\w', re.L))
checks.raises('locale forbids ASCII combination', ValueError, lambda: re.compile(rb'\w', re.L | re.A))
previous_locale = locale.setlocale(locale.LC_CTYPE)
try:
    byte_word = re.compile(rb'\w+', re.L)
    locale.setlocale(locale.LC_CTYPE, 'C')
    eq('locale C bytes', byte_word.findall(b'A_\xe9 8'), [b'A_', b'8'])
finally:
    locale.setlocale(locale.LC_CTYPE, previous_locale)

eq('class and negated class', (re.findall('[Qq]', 'Queue q'), re.findall('[^0-9]', '43a')), (['Q', 'q'], ['3', 'a']))
eq('quantifiers and optional preference', [re.match(p, 'ooo').group() for p in ('o*', 'o+', 'o?', 'o??', 'o{2}', 'o{2,}', 'o{1,2}')], ['ooo', 'ooo', 'o', '', 'oo', 'ooo', 'oo'])
eq('zero and minimum quantifiers', (span(re.match('o*', 'b')), re.match('o+', 'b')), ((0, 0), None))
eq('alternation order', re.match('p|port', 'port').group(), 'p')
eq('noncapturing group', re.match('(?:ab)+(c)', 'ababc').groups(), ('c',))
eq('global flags', re.findall(r'(?imx) ^ port', 'INFO\nPORT'), ['PORT'])
checks.raises('global flags must be at start', re.error, lambda: re.compile('x(?i)y'))
checks.raises('flag removal requires scope', re.error, lambda: re.compile('(?-i)x'))
eq('scoped flags on and off', bool(re.fullmatch('(?i:ab)(?-i:cd)', 'ABcd', re.I)), True)
eq('scoped flag does not leak', re.fullmatch('(?i:ab)(?-i:cd)', 'ABCD', re.I), None)
eq('inline comment', bool(re.fullmatch('p(?# prefix)ort', 'port')), True)
eq('positive lookahead no consumption', span(re.search(r'\w+(?==)', 'port=2')), (0, 4))
eq('negative lookahead rejects suffix', re.findall(r'\bport(?!\w)', 'ports port'), ['port'])
eq('backtracking vs atomic group', (bool(re.fullmatch('(a*)a', 'aa')), re.fullmatch('(?>a*)a', 'aa')), (True, None))
eq('absolute start and multiline caret', (span(re.search('^port', 'x\nport', re.M)), re.search(r'\Aport', 'x\nport', re.M)), ((2, 6), None))
eq('dollar versus strict end', (span(re.search('end$', 'end\n')), re.search(r'end\Z', 'end\n')), ((0, 3), None))
eq('strict end success', span(re.search(r'end\Z', 'end')), (0, 3))
checks.raises('3.12 z anchor unsupported', re.error, lambda: re.compile(r'\z'))
checks.raises('stdlib G anchor unsupported', re.error, lambda: re.compile(r'\G'))
eq('continuous position scanning', fields_without_gaps(re.compile(r'([A-Z])\|'), 'A|B|?C|'), (['A', 'B'], 4))
eq('boundary includes punctuation', span(re.search(r'ue\b', 'queue,')), (3, 5))
eq('non-boundary inside word', span(re.search(r'end\B', 'weekends')), (4, 7))
eq('3.12 empty non-boundary fails', re.search(r'\B', ''), None)
eq('newline tab and escaped literal', bool(re.fullmatch(r'\n\t\.\\', '\n\t.\\')), True)
eq('same group text', bool(re.fullmatch(r'([a-z]+)-\1', 'ready-ready')), True)
eq('reference group ten', bool(re.fullmatch(r'(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)\10', 'abcdefghijj')), True)
checks.raises('missing group ten is an error', re.error, lambda: re.compile(r'(a)\10'))
eq('octal explicit', [bool(re.fullmatch(p, 'A')) for p in (r'\101', r'[\101]', r'\0101')], [True, True, False])
eq('octal with initial zero', bool(re.fullmatch(r'\040', ' ')), True)
eq('replacement reference avoids ambiguity', re.sub(r'(\w+)', r'\g<1>0', 'x'), 'x0')
eq('dot class only dot or LF', re.findall(r'[.\n]', 'x.\r\n'), ['.', '\n'])
eq('any character with complementary classes', re.findall(r'[\s\S]', 'x.\r\n'), ['x', '.', '\r', '\n'])

checks.finish('python3-reg-expressions', interpreter=sys.version, platform=sys.platform,
              protocol='short in-memory str and bytes; no network or subprocess',
              runtime_scope='Python 3.12; Python 3.14 statements are documentation-only')
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 环境

入口文件:projects/python-lab/python3-reg-expressions.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python3-reg-expressions.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 环境。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

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

下载课程关联工程包:Python

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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