Scala 正则表达式
讲解 scala.util.matching.Regex 的构造方式(.r 与 new Regex)、findFirstIn/findAllIn/replaceFirstIn/replaceAllIn 操作、双反斜杠与三重引号转义,以及完整正则语法与实例速查表。
学完这一章,你能够
- 讲解 scala.util.matching.Regex 的构造方式(.r 与 new Regex)、findFirstIn/findAllIn/replaceFirstIn/replaceAllIn 操作、双反斜杠与三重引号转义,以及完整正则语法与实例速查表。
Regex 构造、查找与替换操作
Scala 通过 `scala.util.matching.Regex` 封装底层 Java 正则引擎。构造正则对象既可在字符串上直接调用 `.r`(如 `"Scala".r`),也可显式 `new Regex("(S|s)cala")`。调用 `pattern findFirstIn str` 返回 `Option[String]`(如 `Some(Scala)`,未命中则为 `None`);调用 `pattern findAllIn str` 返回匹配迭代器,配合 `.mkString(",")` 可将 `"Scala is scalable and cool"` 的全部命中拼接为 `Scala,scala`。
文本替换方面,`replaceFirstIn(str, replacement)` 仅替换首个匹配项(如将 `"Scala is scalable and cool"` 替换为 `"Java is scalable and cool"`),而 `replaceAllIn(str, replacement)` 则替换全部匹配片段。此外 `Regex` 对象本身也是提取器,可直接用于 `match` 语句提取捕获分组。
正则语法规则、实例对照与反斜杠转义要点
Scala 正则语法继承自 Java `java.util.regex.Pattern`(主体源自 Perl 风格),涵盖行首尾与输入边界锚点、字符集与反向字符集、贪婪/可选量词、捕获与非捕获分组、预定义字符类及字面量引号区间(详见下方两张完整规则与实例速查表)。
在普通双引号字符串中书写正则时,因反斜杠本身是字符串转义符,每个正则反斜杠都必须双写(例如 `new Regex("abl[ae]\\d+")` 才能把 `\d+` 交给正则引擎,从而在 `"ablaw is able1 and cool"` 中匹配出 `able1`)。若想避免双重转义提升可读性,实际工程中推荐改用三重引号原始字符串写作 `"""abl[ae]\d+""".r`。
Scala 常用正则表达式元字符与语法规则
| 表达式 | 匹配规则说明 |
|---|---|
| ^ | 匹配输入字符串或行首的起始位置。 |
| $ | 匹配输入字符串或行尾的结束位置。 |
| . | 默认匹配除换行符(\r、\n)之外的任意单个字符。 |
| [...] | 字符集,匹配方括号内列出的任意单个字符。 |
| [^...] | 反向字符集,匹配未列在方括号内的任意单个字符。 |
| \\A | 匹配整个输入串开头(不受多行模式影响)。 |
| \\z | 严格匹配整个输入串结尾(不受多行模式影响)。 |
| \\Z | 匹配整个输入串结尾或末尾换行符之前的位置。 |
| re* | 重复匹配前项零次或多次。 |
| re+ | 重复匹配前项一次或多次。 |
| re? | 重复匹配前项零次或一次(可选)。 |
| re{n} | 精确重复匹配前项 n 次。 |
| re{n,} | 至少重复匹配前项 n 次。 |
| re{n,m} | 重复匹配前项 n 到 m 次(含边界)。 |
| a|b | 分支选择,匹配模式 a 或模式 b。 |
| (re) | 捕获分组,匹配 re 并保存捕获文本供提取或反向引用。 |
| (?:re) | 非捕获分组,仅作分组界定而不分配组号。 |
| (?>re) | 原子分组(独立非回溯子表达式),匹配后禁止回溯。 |
| \\w | 匹配单词字符(字母、数字或下划线)。 |
| \\W | 匹配任意非单词字符。 |
| \\s | 匹配任意空白字符(等价于 [ \t\n\r\f])。 |
| \\S | 匹配任意非空白字符。 |
| \\d | 匹配任意十进制数字(等价于 [0-9])。 |
| \\D | 匹配任意非数字字符。 |
| \\G | 匹配上一次匹配结束处的起始锚点。 |
| \\n | 匹配换行符。 |
| \\b | 在字符类外匹配单词边界,在字符类 [...] 内表示退格符。 |
| \\B | 匹配非单词边界位置。 |
| \\t | 匹配水平制表符。 |
| \\Q | 字面量引用开始标记:\Q(a+b)*3\E 原样匹配文本 (a+b)*3。 |
| \\E | 字面量引用结束标记,与 \Q 配对关闭原样字面模式。 |
常见正则表达式模式实例对照表
| 模式实例 | 匹配效果说明 |
|---|---|
| . | 匹配除换行符外的任意单个字符。 |
| [Rr]uby | 匹配 "Ruby" 或 "ruby"。 |
| rub[ye] | 匹配 "ruby" 或 "rube"。 |
| [aeiou] | 匹配任意一个小写元音字母。 |
| [0-9] | 匹配任意一位数字。 |
| [a-z] | 匹配任意一个 ASCII 小写字母。 |
| [A-Z] | 匹配任意一个 ASCII 大写字母。 |
| [a-zA-Z0-9] | 匹配任意 ASCII 字母或数字。 |
| [^aeiou] | 匹配除小写元音字母以外的字符。 |
| [^0-9] | 匹配除数字以外的字符。 |
| \\d | 匹配数字(等价 [0-9])。 |
| \\D | 匹配非数字(等价 [^0-9])。 |
| \\s | 匹配空白符(空格、制表符、换行等)。 |
| \\S | 匹配非空白字符。 |
| \\w | 匹配字母、数字或下划线。 |
| \\W | 匹配非字母、数字、下划线字符。 |
| ruby? | 匹配 "rub" 或 "ruby"(y 出现 0 或 1 次)。 |
| ruby* | 匹配 "rub" 后跟 0 个或多个 y。 |
| ruby+ | 匹配 "rub" 后跟 1 个或多个 y。 |
| \\d{3} | 连续匹配恰好 3 位数字。 |
| \\d{3,} | 连续匹配 3 位或更多数字。 |
| \\d{3,5} | 连续匹配 3 位、4 位或 5 位数字。 |
| \\D\\d+ | 无分组:1 个非数字后紧跟 1 个或多个数字。 |
| (\\D\\d)+/ | 分组重复:1 组或多组“非数字+数字”对后接斜杠 /。 |
| ([Rr]uby(, )?)+ | 匹配单个或以逗号空格分隔的多个 Ruby/ruby 序列。 |
离线校验 Scala Regex 查找、替换、分组提取与字符类量词
"""Offline Scala semantic verification lab for Chapter 22 (regular-expressions)."""
import json
import re
VERSION = "CPython 3.12.14 offline Scala 2.13/3 semantic verifier (scalac absent)"
def case_find_first_and_find_all_mkstring():
m1 = re.search(r"Scala", "Scala is Scalable and cool")
first_opt = f"Some({m1.group(0)})" if m1 else "None"
all_matches = [m.group(0) for m in re.finditer(r"(?:S|s)cala", "Scala is scalable and cool")]
expected = {
"find_first": "Some(Scala)",
"find_all_mkstring": "Scala,scala",
}
actual = {
"find_first": first_opt,
"find_all_mkstring": ",".join(all_matches),
}
return {
"name": "find_first_and_find_all_mkstring",
"summary": "验证 Regex.findFirstIn 返回 Option 与 findAllIn.mkString(\",\") 拼接全部匹配项",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_replace_first_and_replace_all():
pat = re.compile(r"(?:S|s)cala")
src = "Scala is scalable and cool"
rep_first = pat.sub("Java", src, count=1)
rep_all = pat.sub("Java", src)
expected = {
"replace_first": "Java is scalable and cool",
"replace_all": "Java is Javable and cool",
}
actual = {
"replace_first": rep_first,
"replace_all": rep_all,
}
return {
"name": "replace_first_and_replace_all",
"summary": "验证 replaceFirstIn 仅替换首个匹配项与 replaceAllIn 替换全部匹配项的差异",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_regex_quantifiers_groups_and_escapes():
# Source example: new Regex("abl[ae]\\d+") on "ablaw is able1 and cool"
abl_matches = re.findall(r"abl[ae]\d+", "ablaw is able1 and cool")
# Capturing group extraction (equivalent to Scala Regex unapplySeq)
date_m = re.fullmatch(r"(\d{4})-(\d{2})-(\d{2})", "2026-12-01")
non_cap = re.findall(r"(?:[Rr]uby)", "Ruby and ruby")
quoted_lit = re.search(re.escape("(a+b)*3"), "calc (a+b)*3 done")
expected = {
"abl_digits": ["able1"],
"date_groups": ("2026", "12", "01"),
"non_capturing": ["Ruby", "ruby"],
"literal_quote_match": "(a+b)*3",
}
actual = {
"abl_digits": abl_matches,
"date_groups": date_m.groups() if date_m else (),
"non_capturing": non_cap,
"literal_quote_match": quoted_lit.group(0) if quoted_lit else "",
}
return {
"name": "regex_quantifiers_groups_and_escapes",
"summary": "验证字符类+量词(abl[ae]\\d+)、捕获/非捕获分组以及字面量转义(\\Q...\\E 等价)行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_char_classes_and_word_boundaries():
d3 = re.findall(r"\b\d{3}\b", "12 345 6789 007")
d3_5 = re.findall(r"\b\d{3,5}\b", "12 345 6789 123456")
ruby_opt = [bool(re.fullmatch(r"ruby?", s)) for s in ("rub", "ruby", "rubyy")]
neg_vowels = re.findall(r"[^aeiou]", "plain")
expected = {
"exact_3_digits": ["345", "007"],
"range_3_5_digits": ["345", "6789"],
"ruby_optional_y": [True, True, False],
"non_vowels_in_plain": ["p", "l", "n"],
}
actual = {
"exact_3_digits": d3,
"range_3_5_digits": d3_5,
"ruby_optional_y": ruby_opt,
"non_vowels_in_plain": neg_vowels,
}
return {
"name": "char_classes_and_word_boundaries",
"summary": "验证 \\d/\\b 单词边界、{n}/{n,m} 重复次数、? 可选量词与反向字符集 [^aeiou]",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_find_first_and_find_all_mkstring(),
case_replace_first_and_replace_all(),
case_regex_quantifiers_groups_and_escapes(),
case_char_classes_and_word_boundaries(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 在 CPython 3.12.14 离线脚本中验证 findFirstIn/findAllIn.mkString、replaceFirstIn/replaceAllIn、abl[ae]\d+ 与词边界/量词全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。
当前源码 SHA256:55232598fe4f944ec865d64b116979b28945cac9cdb11b08286bcb0c8ed03326
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。
ZIP SHA256:4c04f5fe733b7e98862c5c8873acc6fb38d918791051c700e99b4b5e4d168831
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么用三重引号 `"""\d{4}-\d{2}-\d{2}""".r` 定义 Scala 正则比普通双引号更不容易出错?
展开参考解答
普通双引号字符串会先执行一层 Scala 转义解析,导致每个正则反斜杠都必须写成 `\\`;三重引号原始字符串不解析反斜杠转义,可直接按正则原貌书写 `\d`。