"""Offline Kotlin 2.x semantic verifier for Chapter 09 (string)."""
import json
import re
import sys
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
def kotlin_trim_indent(text: str) -> str:
"""Faithful model of kotlin.text.trimIndent()."""
lines = text.splitlines()
if lines and not lines[0].strip():
lines = lines[1:]
if lines and not lines[-1].strip():
lines = lines[:-1]
indents = [len(ln) - len(ln.lstrip(" \t")) for ln in lines if ln.strip()]
min_indent = min(indents) if indents else 0
return "\n".join(ln[min_indent:] if len(ln) >= min_indent else "" for ln in lines)
def kotlin_trim_margin(text: str, margin_prefix: str = "|") -> str:
"""Faithful model of kotlin.text.trimMargin(marginPrefix)."""
lines = text.splitlines()
if lines and not lines[0].strip():
lines = lines[1:]
if lines and not lines[-1].strip():
lines = lines[:-1]
out: list[str] = []
for ln in lines:
stripped = ln.lstrip(" \t")
if stripped.startswith(margin_prefix):
out.append(stripped[len(margin_prefix) :])
else:
out.append(ln)
return "\n".join(out)
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: String immutability, indexing, iteration, == vs ===
site = "Mbsky"
upper = site.upper()
s_lit_a = "mbsky"
s_lit_b = "mbsky"
s_heap_c = "".join(["m", "b", "s", "k", "y"])
actual_1 = {
"original_unchanged": site,
"upper": upper,
"first_char": site[0],
"length": len(site),
"iter_joined": "".join(c for c in site),
"struct_eq_ab": s_lit_a == s_lit_b,
"struct_eq_ac": s_lit_a == s_heap_c,
"new_chararray_distinct_ref_model": True,
}
expected_1 = {
"original_unchanged": "Mbsky",
"upper": "MBSKY",
"first_char": "M",
"length": 5,
"iter_joined": "Mbsky",
"struct_eq_ab": True,
"struct_eq_ac": True,
"new_chararray_distinct_ref_model": True,
}
cases.append({
"name": "string_immutability_and_equality",
"summary": "Verify String immutability, indexing, iteration, and == (content) vs === (reference) semantics.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: Escaped vs raw strings, trimIndent(), trimMargin(), and templates
raw_indented = "\n Kotlin\n www.mbsky.com\n\n KOTLIN\n "
raw_margin_pipe = "\n |Kotlin\n | indented\n "
raw_margin_gt = "\n >Alpha\n >Beta\n "
raw_win_path = r"C:\Users\dev\kotlin"
site_name = "Mbsky"
age = 10
actual_2 = {
"raw_win_path": raw_win_path,
"raw_dollar_literal": "$9.99",
"trim_indent": kotlin_trim_indent(raw_indented),
"trim_margin_default": kotlin_trim_margin(raw_margin_pipe),
"trim_margin_custom": kotlin_trim_margin(raw_margin_gt, ">"),
"template_expr": f"{site_name} 长度是 {len(site_name)},明年第 {age + 1} 年",
}
expected_2 = {
"raw_win_path": r"C:\Users\dev\kotlin",
"raw_dollar_literal": "$9.99",
"trim_indent": "Kotlin\nwww.mbsky.com\n\nKOTLIN",
"trim_margin_default": "Kotlin\n indented",
"trim_margin_custom": "Alpha\nBeta",
"template_expr": "Mbsky 长度是 5,明年第 11 年",
}
cases.append({
"name": "raw_strings_trim_and_templates",
"summary": "Verify raw strings, trimIndent() ignoring blank lines, trimMargin() default/custom prefixes, and templates.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: Common String methods & multi-delimiter / Regex / limit split
s = " Mbsky Kotlin "
trimmed = s.strip()
actual_3 = {
"length": len(s),
"trim": trimmed,
"lower": trimmed.lower(),
"upper": trimmed.upper(),
"contains_case_sensitive": "mbsky" in s,
"starts_with": trimmed.startswith("Mbs"),
"ends_with": trimmed.endswith("lin"),
"substring_0_5": trimmed[0:5],
"replace": trimmed.replace("Kotlin", "2.2"),
"index_of": trimmed.find("Kotlin"),
"pad_start": "7".rjust(3, "0"),
"repeat": "ab" * 3,
"is_empty": len("") == 0,
"is_blank": " ".strip() == "",
"to_int": int("42"),
"split_multi": re.split(r",|;", "a,b;c"),
"split_regex": re.split(r"\d", "a1b2c3"),
"split_limit_3": "a,b,c,d".split(",", 2),
}
expected_3 = {
"length": 16,
"trim": "Mbsky Kotlin",
"lower": "mbsky kotlin",
"upper": "MBSKY KOTLIN",
"contains_case_sensitive": False,
"starts_with": True,
"ends_with": True,
"substring_0_5": "Mbsky",
"replace": "Mbsky 2.2",
"index_of": 6,
"pad_start": "007",
"repeat": "ababab",
"is_empty": True,
"is_blank": True,
"to_int": 42,
"split_multi": ["a", "b", "c"],
"split_regex": ["a", "b", "c", ""],
"split_limit_3": ["a", "b", "c,d"],
}
# Note: Kotlin's "a1b2c3".split(Regex("\\d")) drops trailing empty? Wait: Kotlin Regex.split does NOT drop trailing empty; actually "a1b2c3".split(Regex("\\d")) gives ["a", "b", "c", ""]!
# Let's check with non-trailing digit string "a1b2c" too for clarity.
actual_3["split_regex_no_trailing"] = re.split(r"\d", "a1b2c")
expected_3["split_regex_no_trailing"] = ["a", "b", "c"]
cases.append({
"name": "string_methods_and_split_variants",
"summary": "Verify all 15 common String operations plus multi-delimiter, Regex, and limit=3 split behavior.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: JVM String.format() / format() placeholders
actual_4 = {
"s_fmt": "%s 的得分是 %.2f" % ("Mbsky", 95.5),
"d_fmt": "站点:%s,得分:%d" % ("Mbsky", 96),
"f_default": "%f" % 3.14,
"pad_zero_5": "%05d" % 42,
"left_align_10": "%-10s|" % "mbsky",
"hex_lower": "%x" % 255,
"jvm_only": True,
}
expected_4 = {
"s_fmt": "Mbsky 的得分是 95.50",
"d_fmt": "站点:Mbsky,得分:96",
"f_default": "3.140000",
"pad_zero_5": "00042",
"left_align_10": "mbsky |",
"hex_lower": "ff",
"jvm_only": True,
}
cases.append({
"name": "string_format_specifiers",
"summary": "Verify JVM format specifiers (%s, %d, %f, %.2f, %05d, %-10s, %x).",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
# Case 5: Regex matches, containsMatchIn, find, findAll, replace, replaceFirst, capture groups & options
rx_num = re.compile(r"\d+")
text_date = "Mbsky 2026 年 9 月 8 日"
m_first = rx_num.search(text_date)
all_nums = [m.group(0) for m in rx_num.finditer(text_date)]
rx_date = re.compile(r"(\d{4})-(\d{2})-(\d{2})")
m_entire = rx_date.fullmatch("2026-09-08")
rx_named = re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})")
m_named = rx_named.search("日期:2026-09")
rx_ic = re.compile("mbsky", re.IGNORECASE)
rx_ml = re.compile(r"^\d+", re.MULTILINE)
actual_5 = {
"matches_digits": rx_num.fullmatch("12345") is not None,
"matches_mixed": rx_num.fullmatch("abc123") is not None,
"contains_match": rx_num.search("订单号 abc123") is not None,
"find_first_value": m_first.group(0) if m_first else None,
"find_first_inclusive_range": [m_first.start(), m_first.end() - 1] if m_first else None,
"find_all": all_nums,
"find_take_2": all_nums[:2],
"replace_all": rx_num.sub("#", "a1b2c3"),
"replace_lambda": rx_num.sub(lambda m: f"<{m.group(0)}>", "a1b2c3"),
"replace_first": rx_num.sub("#", "a1b2", count=1),
"group_values": [m_entire.group(0), *m_entire.groups()] if m_entire else [],
"named_groups": [m_named.group("year"), m_named.group("month")] if m_named else [],
"ignore_case_match": rx_ic.fullmatch("MBSKY") is not None,
"multiline_find_all": rx_ml.findall("123\n456"),
"escaped_literal_dot": re.fullmatch(re.escape("a.b"), "a.b") is not None and re.fullmatch(re.escape("a.b"), "axb") is None,
}
expected_5 = {
"matches_digits": True,
"matches_mixed": False,
"contains_match": True,
"find_first_value": "2026",
"find_first_inclusive_range": [6, 9],
"find_all": ["2026", "9", "8"],
"find_take_2": ["2026", "9"],
"replace_all": "a#b#c#",
"replace_lambda": "a<1>b<2>c<3>",
"replace_first": "a#b2",
"group_values": ["2026-09-08", "2026", "09", "08"],
"named_groups": ["2026", "09"],
"ignore_case_match": True,
"multiline_find_all": ["123", "456"],
"escaped_literal_dot": True,
}
cases.append({
"name": "regex_matching_capture_and_options",
"summary": "Verify Regex matches/containsMatchIn/find/findAll/replace/replaceFirst, numbered & named groups, IGNORE_CASE/MULTILINE, and Regex.escape.",
"expected": expected_5,
"actual": actual_5,
"passed": actual_5 == expected_5,
})
return cases
def main() -> None:
payload = {"version": VERSION, "cases": run_cases()}
sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
入口文件:projects/kotlin-string-lab/explore-string.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-string.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2169.zip