Kotlin 字符串与正则
全面掌握 Kotlin 不可变 String、转义与三引号原始字符串、trimIndent/trimMargin、字符串模板、15 个常用字符串方法、JVM 格式化占位符及 Regex 匹配、替换、捕获组与选项。
学完这一章,你能够
- 全面掌握 Kotlin 不可变 String、转义与三引号原始字符串、trimIndent/trimMargin、字符串模板、15 个常用字符串方法、JVM 格式化占位符及 Regex 匹配、替换、捕获组与选项。
字符串不可变性、下标遍历与相等比较
Kotlin 使用不可变类型 `String` 表示文本:所有形似修改的方法(如 `uppercase()`、`replace()`)都会返回全新字符串实例而原串不变,可通过 `site[0]` 按下标读取字符或直接 `for (c in site)` 遍历。比较字符串内容一律使用 `==`(结构相等),切勿用 `===`(引用相等,运行期通过 `String(charArrayOf(...))` 新建的对象即使内容一致,`===` 也返回 `false`)。由于不可变性会在循环高频拼接时产生大量临时对象,循环拼接应改用 `StringBuilder`。
转义字符串、原始字符串、trimIndent/trimMargin 与模板
Kotlin 区分两类字符串字面量:双引号转义字符串支持 `\n`、`\t` 等转义序列;三引号原始字符串 `"""..."""` 原样保留换行、反斜杠与双引号,非常适合编写 Windows 路径、JSON 片段和正则表达式。唯一注意点是原始字符串同样启用 `$` 模板插值且不支持反斜杠转义,需输出字面量 `$` 时写作 `${'$'}`。
多行原始字符串常配合缩进裁剪方法使用:`trimIndent()` 自动剥离首尾空行并按所有非空行的最小公共缩进裁剪左侧空白(中间空行不影响公共缩进计算);`trimMargin(prefix)` 则默认以竖线 `|`(亦可自定义为 `>` 等字符)为边界前缀,移除每行前缀及其左侧空白,适合精确保留部分相对缩进。
字符串模板以 `$` 引导:单个变量写 `$siteName`,属性访问、算术或方法调用写 `${siteName.length}`、`${age + 1}`、`${siteName.uppercase()}`;在转义字符串中输出字面量美元符号写 `\$`。当变量名紧跟后续英文字母时务必用 `${siteName}Suffix` 划定边界,防止编译器将整段拼成一个不存在的变量名。
常用字符串方法与 JVM 格式化
标准库为 `String` 提供了丰富的只读与转换 API,包括属性 `length`,以及 `isEmpty()`、`isBlank()`、`lowercase()`、`uppercase()`、`trim()`、`split()`、`replace()`、`substring()`、`padStart()`、`repeat()`、`startsWith()`、`endsWith()`、`contains()`(默认区分大小写)、`indexOf()` 和 `toInt()`。其中 `split()` 还支持一次传入多个分隔符(如 `split(",", ";")`)、传入 `Regex` 以及通过 `limit` 参数限制切分份数(最后一项保留剩余全部文本)。
在 JVM 平台可调用 `String.format(fmt, ...)` 或扩展函数 `"...".format(...)` 实现对齐、左侧补零与小数精度控制,占位符语法与 Java 一致。需注意 `String.format` 依赖 JVM 实现,在 Kotlin/JS 与 Kotlin/Native 上不可用,跨平台代码应改用字符串模板或自定义补位函数。
正则表达式 Regex 完整用法
Kotlin 通过 `Regex("""\d+""")` 或 `"""\d+""".toRegex()` 创建正则表达式(推荐搭配三引号原始字符串避免双重反斜杠)。`matches()` 要求整个输入串完全匹配,`containsMatchIn()` 检查任意子串命中;`find()` 返回首个 `MatchResult?`(包含 `.value` 文本与闭区间 `.range` 下标),`findAll()` 则返回惰性 `Sequence<MatchResult>`,可链式配合 `.take(2).map { it.value }.toList()` 按需提取。
修改与切分文本时可使用 `replace()`(支持固定替换串或基于 `MatchResult` 的 Lambda 动态替换)、`replaceFirst()` 以及 `str.split(regex)`。圆括号用于声明捕获组,`matchEntire()` 要求全串匹配并返回 `MatchResult?`(区别于只返回 `Boolean` 的 `matches()`),其中 `groupValues[0]` 为整体匹配,后续下标对应各捕获组;也支持命名捕获组 `(?<year>\d{4})` 并通过 `groups["year"]?.value` 取值。可通过 `RegexOption.IGNORE_CASE`、`RegexOption.MULTILINE`(多选项用 `setOf(...)`)调整匹配模式;需匹配 `.`、`*`、`+`、`?`、`(` 等元字符字面量时应反斜杠转义或调用 `Regex.escape()`。
字符串与正则常见问题
日常最易困惑的五类问题包括:一是调用 `replace` 等方法后原串不变,因 `String` 不可变必须接收返回值;二是原始字符串输出 `$` 写 `${'$'}`、转义字符串写 `\$`;三是少量拼接优先字符串模板、循环高频拼接必须换 `StringBuilder`;四是 `matches()` 全串匹配返 `Boolean` 而 `find()` 局部匹配返 `MatchResult?`;五是三引号原始字符串写正则只需单个反斜杠,比普通双引号 `"\\d+"` 更直观且不易出错。
Kotlin String 常用属性与方法速查
| 方法 | 说明 | 示例 |
|---|---|---|
| length | 字符个数(属性而非方法) | "mbsky".length 得到 5 |
| isEmpty() | 判断长度是否为 0 | "".isEmpty() 得到 true |
| isBlank() | 判断是否为空或仅含空白字符 | " ".isBlank() 得到 true |
| lowercase() | 返回全小写新字符串 | "MBSKY".lowercase() 得到 mbsky |
| uppercase() | 返回全大写新字符串 | "mbsky".uppercase() 得到 MBSKY |
| trim() | 去除首尾空白字符 | " Mbsky ".trim() 得到 Mbsky |
| split() | 按分隔符或正则切分为 List | "a,b".split(",") 得到 [a, b] |
| replace() | 替换全部匹配子串 | "a-b".replace("-", "+") 得到 a+b |
| substring() | 按左闭右开区间截取子串 | "Mbsky".substring(0, 3) 得到 Mbs |
| padStart() | 在左侧补齐指定字符至目标长度 | "7".padStart(3, '0') 得到 007 |
| repeat() | 将字符串重复指定次数 | "ab".repeat(3) 得到 ababab |
| startsWith() | 判断是否以指定前缀开头 | "Mbsky".startsWith("Mbs") 得到 true |
| contains() | 判断是否包含子串(默认区分大小写) | "Mbsky".contains("mbsky") 得到 false |
| indexOf() | 返回首次出现下标,未找到返回 -1 | "Mbsky Kotlin".indexOf("Kotlin") 得到 6 |
| toInt() | 解析为 Int 整数,非法格式抛异常 | "42".toInt() 得到 42 |
JVM 字符串格式化常用占位符
| 占位符 | 含义 | 示例结果 |
|---|---|---|
| %s | 字符串 | "%s".format("Mbsky") 得到 Mbsky |
| %d | 十进制整数 | "%d".format(96) 得到 96 |
| %f | 浮点数,默认保留 6 位小数 | "%f".format(3.14) 得到 3.140000 |
| %.2f | 保留两位小数 | "%.2f".format(95.5) 得到 95.50 |
| %05d | 宽度 5,不足左侧补 0 | "%05d".format(42) 得到 00042 |
| %-10s | 宽度 10,左对齐右侧补空格 | "%-10s|".format("mbsky") 得到 "mbsky |" |
| %x | 十六进制小写输出 | "%x".format(255) 得到 ff |
离线校验 String 不可变性、trimIndent/trimMargin、15 项方法、format 与 Regex 捕获组
"""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()
- 离线脚本确认 String 不可变与判等、原始字符串裁剪算法、全部常用方法与 split 变体、7 类 format 占位符及 Regex 匹配/替换/命名组/选项全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
当前源码 SHA256:c7be983fa46cc3e54f42e2c846a1dcccbdcc2ce300845f8daefd76ad7530926c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
ZIP SHA256:3062418e3b903f81be7c61d1144da0b941a449873bdee6f4e5268b242142ee74
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Kotlin 中,如何区分 `isEmpty()` 与 `isBlank()`,以及 `Regex.matches()` 与 `Regex.find()` 的核心区别?
展开参考解答
`isEmpty()` 仅在长度为 0 时为 `true`,`isBlank()` 在仅包含空格或制表符等空白字符时也为 `true`;`matches()` 要求整个字符串完全匹配并返回 `Boolean`,`find()` 在任意子串匹配时即返回 `MatchResult?`。