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

离线校验 Perl m//、s///、tr/// 及正则元字符贪婪/惰性语义

PYTHONWindows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。explore-regular-expressions.py
explore-regular-expressions.py210 行
"""Offline Perl 5 semantic verification lab for Chapter 21 (regular-expressions)."""
import json
import re

VERSION = "CPython 3.12.14 offline Perl 5 semantic verifier (perl absent)"


def perl_tr(s: str, search: str, replace: str, flags: str = "") -> str:
    """Emulate Perl tr/// with /c (complement), /d (delete), /s (squeeze)."""
    def expand(spec: str) -> list[str]:
        out = []
        i = 0
        while i < len(spec):
            if i + 2 < len(spec) and spec[i + 1] == "-":
                out.extend(chr(c) for c in range(ord(spec[i]), ord(spec[i + 2]) + 1))
                i += 3
            else:
                out.append(spec[i])
                i += 1
        return out

    src_list = expand(search)
    rep_list = expand(replace)
    src_set = set(src_list)
    comp = "c" in flags
    delete = "d" in flags
    squeeze = "s" in flags

    mapping = {}
    if not comp:
        for idx, ch in enumerate(src_list):
            if idx < len(rep_list):
                mapping[ch] = rep_list[idx]
            elif rep_list and not delete:
                mapping[ch] = rep_list[-1]
            elif delete:
                mapping[ch] = None
            else:
                mapping[ch] = ch

    result = []
    last_replaced = None
    for ch in s:
        if comp:
            in_target = ch not in src_set
            if in_target:
                if delete and not rep_list:
                    last_replaced = None
                    continue
                out_ch = rep_list[-1] if rep_list else ch
                if squeeze and last_replaced == out_ch:
                    continue
                result.append(out_ch)
                last_replaced = out_ch
            else:
                result.append(ch)
                last_replaced = None
        else:
            if ch in src_set:
                out_ch = mapping[ch]
                if out_ch is None:
                    last_replaced = None
                    continue
                if squeeze and last_replaced == out_ch:
                    continue
                result.append(out_ch)
                last_replaced = out_ch
            else:
                result.append(ch)
                last_replaced = None
    return "".join(result)


def case_match_operator_modifiers_and_vars():
    s = "welcome to bluesky site."
    m = re.search(r"blue", s)
    pre, hit, post = s[: m.start()], m.group(0), s[m.end() :]
    ci_hit = bool(re.search(r"BLUESKY", s, re.I))
    ml_hits = re.findall(r"^item\d+", "item1\nitem2\n", re.M)
    dotall_hit = bool(re.search(r"a.b", "a\nb", re.S))
    verbose_hit = bool(re.search(r" blue  sky ", s, re.X))
    expected = {
        "prematch": "welcome to ",
        "match": "blue",
        "postmatch": "sky site.",
        "reconstructed": True,
        "ci_hit": True,
        "ml_hits": ["item1", "item2"],
        "dotall_hit": True,
        "verbose_hit": True,
    }
    actual = {
        "prematch": pre,
        "match": hit,
        "postmatch": post,
        "reconstructed": (pre + hit + post) == s,
        "ci_hit": ci_hit,
        "ml_hits": ml_hits,
        "dotall_hit": dotall_hit,
        "verbose_hit": verbose_hit,
    }
    return {
        "name": "match_operator_modifiers_and_vars",
        "summary": "验证 m// 匹配操作符、/i /m /s /x /g 修饰符及 $`/$&/$' 匹配切分重组",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_substitution_operator_and_modifiers():
    s1 = "welcome to portal site."
    sub_once = re.sub(r"portal", "bluesky", s1, count=1)
    s2 = "cat CAT cat"
    sub_gi = re.sub(r"cat", "dog", s2, flags=re.I)
    # /e modifier evaluates replacement expression
    s3 = "price=10 tax=5"
    sub_eval = re.sub(r"\d+", lambda m: str(int(m.group(0)) * 2), s3)
    expected = {
        "sub_once": "welcome to bluesky site.",
        "sub_gi": "dog dog dog",
        "sub_eval": "price=20 tax=10",
    }
    actual = {
        "sub_once": sub_once,
        "sub_gi": sub_gi,
        "sub_eval": sub_eval,
    }
    return {
        "name": "substitution_operator_and_modifiers",
        "summary": "验证 s/// 单次替换、/gi 全局不区分大小写替换以及 /e 表达式求值替换",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_transliteration_operator_tr():
    upper = perl_tr("welcome to bluesky site.", "a-z", "A-Z")
    squeezed = perl_tr("boooookkeeper", "a-z", "a-z", "s")
    deleted_ws = perl_tr("a\tb c\t d", "\t ", "", "d")
    digits_spaced = perl_tr("id:42--code:99!", "0-9", " ", "cs")
    # Note: Perl tr/\d/ /c treats \d as literal 'd', not digit class
    expected = {
        "upper": "WELCOME TO BLUESKY SITE.",
        "squeezed": "bokeper",
        "deleted_ws": "abcd",
        "digits_spaced": " 42 99 ",
    }
    actual = {
        "upper": upper,
        "squeezed": squeezed,
        "deleted_ws": deleted_ws,
        "digits_spaced": digits_spaced,
    }
    return {
        "name": "transliteration_operator_tr",
        "summary": "验证 tr/// 字符表映射、/s 去重压缩、/d 删除与 /cs 补集压缩行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_regex_metacharacters_and_quantifiers():
    # Greedy * / + vs lazy *? / +?
    greedy = re.search(r"<.+>", "<a><b>").group(0)
    lazy = re.search(r"<.+?>", "<a><b>").group(0)
    quant = re.findall(r"\d{2,3}", "1 22 333 4444")
    word_b = re.findall(r"\bcat\b", "cat scatter catalog cat")
    groups = re.search(r"(\w+)-(\d+)", "node-404").groups()
    escaped = bool(re.search(r"a\*b", "a*b")) and not bool(re.search(r"a\*b", "aaab"))
    expected = {
        "greedy_plus": "<a><b>",
        "lazy_plus": "<a>",
        "quant_2_3": ["22", "333", "444"],
        "word_boundary": ["cat", "cat"],
        "capture_groups": ["node", "404"],
        "escaped_star": True,
    }
    actual = {
        "greedy_plus": greedy,
        "lazy_plus": lazy,
        "quant_2_3": quant,
        "word_boundary": word_b,
        "capture_groups": list(groups),
        "escaped_star": escaped,
    }
    return {
        "name": "regex_metacharacters_and_quantifiers",
        "summary": "验证元字符、贪婪(+/*)与惰性(+?/*?)量词差异、词边界 \\b、分组捕获与反斜杠转义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_match_operator_modifiers_and_vars(),
        case_substitution_operator_and_modifiers(),
        case_transliteration_operator_tr(),
        case_regex_metacharacters_and_quantifiers(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。

入口文件:projects/perl-regular-expressions-lab/explore-regular-expressions.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-regular-expressions.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Perl

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

下载课程关联工程包:Perl

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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