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

离线校验 Ruby 正则修饰符、贪婪/非贪婪量词、锚点、反向引用与 sub/gsub

PYTHONWindows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。explore-regular-expressions.py
explore-regular-expressions.py166 行
"""Offline Ruby 3.x semantic verification lab for Chapter 32 (regular-expressions)."""
import json
import re

VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"


def case_regex_modifiers_and_delimiters():
    line1 = "Cats are smarter than dogs"
    line2 = "Dogs also like meat"
    m1 = re.search(r"Cats(.*)", line1)
    m2 = re.search(r"Cats(.*)", line2)

    # Ruby /m makes '.' match '\n' (equivalent to Python re.DOTALL)
    dot_default = re.search(r"a.b", "a\nb") is not None
    dot_multiline = re.search(r"a.b", "a\nb", flags=re.DOTALL) is not None
    ignore_case = re.search(r"</(.*)>", "</HTML>", flags=re.IGNORECASE).group(1)
    verbose_x = re.search(
        r"""
        (\d{3}) # area
        -
        (\d{4})
        """,
        "010-2026",
        flags=re.VERBOSE,
    ).groups()

    expected = {
        "line1_match_index": 0,
        "line2_match": None,
        "dot_without_m": False,
        "dot_with_m": True,
        "percent_r_ignore_case": "HTML",
        "verbose_x_groups": ["010", "2026"],
    }
    actual = {
        "line1_match_index": m1.start() if m1 else None,
        "line2_match": m2.start() if m2 else None,
        "dot_without_m": dot_default,
        "dot_with_m": dot_multiline,
        "percent_r_ignore_case": ignore_case,
        "verbose_x_groups": list(verbose_x),
    }
    return {
        "name": "regex_modifiers_and_delimiters",
        "summary": "核验 =~ 匹配索引、/i/m/x 修饰符(特别是 Ruby /m 等价于 DOTALL)与 %r 自定义分隔符语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_char_classes_quantifiers_anchors():
    greedy = re.search(r"<.*>", "<ruby>perl>").group(0)
    lazy = re.search(r"<.*?>", "<ruby>perl>").group(0)
    digits_3_5 = re.findall(r"\d{3,5}", "12 123 12345")
    boundary_hits = [w for w in ("rube", "ruby", "rub") if re.search(r"\brub\B", w)]
    # \A vs ^ on multi-line text
    text_ml = "first\nRuby"
    caret_hits = bool(re.search(r"^Ruby", text_ml, flags=re.MULTILINE))
    string_start_hits = bool(re.search(r"\ARuby", text_ml, flags=re.MULTILINE))
    expected = {
        "greedy": "<ruby>perl>",
        "lazy": "<ruby>",
        "digits_3_5": ["123", "12345"],
        "non_word_boundary": ["rube", "ruby"],
        "caret_matches_line": True,
        "backslash_A_matches_string_only": False,
    }
    actual = {
        "greedy": greedy,
        "lazy": lazy,
        "digits_3_5": digits_3_5,
        "non_word_boundary": boundary_hits,
        "caret_matches_line": caret_hits,
        "backslash_A_matches_string_only": string_start_hits,
    }
    return {
        "name": "char_classes_quantifiers_anchors",
        "summary": "核验贪婪/非贪婪量词、字符类与 \\A/\\Z/\\z/^/$/\\b/\\B 位置锚点语义差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_groups_backrefs_and_lookahead():
    backref_ok = bool(re.fullmatch(r"([Rr])uby&\1ails", "Ruby&Rails"))
    backref_mismatch = bool(re.fullmatch(r"([Rr])uby&\1ails", "Ruby&rails"))
    pos_lookahead = re.findall(r"Ruby(?=!)", "Ruby! Ruby?")
    neg_lookahead = re.findall(r"Ruby(?!!)", "Ruby! Ruby?")
    named = re.search(r"(?P<lang>[A-Za-z]+)-(?P<ver>\d+\.\d+)", "Ruby-3.3").groupdict()
    non_capturing = re.search(r"rub(?:y|le)", "ruble").groups()

    expected = {
        "backref_ok": True,
        "backref_mismatch": False,
        "pos_lookahead": ["Ruby"],
        "neg_lookahead": ["Ruby"],
        "named_captures": {"lang": "Ruby", "ver": "3.3"},
        "non_capturing_groups": [],
    }
    actual = {
        "backref_ok": backref_ok,
        "backref_mismatch": backref_mismatch,
        "pos_lookahead": pos_lookahead,
        "neg_lookahead": neg_lookahead,
        "named_captures": named,
        "non_capturing_groups": list(non_capturing),
    }
    return {
        "name": "groups_backrefs_and_lookahead",
        "summary": "核验捕获分组、\\1 反向引用、(?:...) 非捕获分组、命名捕获与正负先行断言",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_sub_gsub_and_bang_semantics():
    phone = "138-3453-1111 #这是一个电话号码"
    step1 = re.sub(r"#.*$", "", phone, count=1)
    step2 = re.sub(r"\D", "", step1)

    text = "rails 是 rails,  Ruby on Rails 非常好的 Ruby 框架"
    sub_once = re.sub(r"\brails\b", "Rails", text, count=1)
    gsub_all = re.sub(r"\brails\b", "Rails", text)
    # In Ruby, sub!/gsub! return nil when no substitution occurred
    no_change_bang = None if re.subn(r"python", "Ruby", text)[1] == 0 else text

    expected = {
        "after_strip_comment": "138-3453-1111 ",
        "digits_only": "13834531111",
        "sub_once": "Rails 是 rails,  Ruby on Rails 非常好的 Ruby 框架",
        "gsub_all": "Rails 是 Rails,  Ruby on Rails 非常好的 Ruby 框架",
        "bang_no_match_returns_nil": None,
    }
    actual = {
        "after_strip_comment": step1,
        "digits_only": step2,
        "sub_once": sub_once,
        "gsub_all": gsub_all,
        "bang_no_match_returns_nil": no_change_bang,
    }
    return {
        "name": "sub_gsub_and_bang_semantics",
        "summary": "核验 sub 与 gsub 首次/全局替换行为,以及 sub!/gsub! 未发生替换时返回 nil 的边界语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_regex_modifiers_and_delimiters(),
        case_char_classes_quantifiers_anchors(),
        case_groups_backrefs_and_lookahead(),
        case_sub_gsub_and_bang_semantics(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


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

运行环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。

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

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

下载课程关联工程包:Ruby

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

下载课程关联工程包:Ruby

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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