Wing 语言 std.regex 模块实战:从编译到测试的完整正则表达式指南

原创2026-10-14 19:30:231,767 阅读
文章标签:编程语言编译器云原生语言运行时

Wing 语言 std.regex 模块实战:从编译到测试的完整正则表达式指南

本篇文章围绕 Wing 云端编程语言标准库中的 std.regex 模块展开,以仓库内 SDK 测试用例(tests/sdk_tests/std/regex.test.w)及其 hangar 测试快照为核心,系统讲解正则表达式的编译、匹配、查找、分组捕获与替换等全部 API,并结合源码实现与测试验证流程,帮助你掌握在 Wing 中处理字符串正则任务的完整实战能力。

从测试用例看 Wing 正则表达式能力全景

Wing 语言内置了对正则表达式的原生支持。在 Wing 的官方 SDK 测试集中,regex.test.w 是一份极具代表性的测试文件,它用 expect 断言库覆盖了 std.regex 模块的全部核心能力,包括:

  • 编译正则模式(regex.compile);
  • 判断是否存在匹配(test);
  • 查找第一个匹配(find);
  • 查找所有不重叠匹配(findAll);
  • 获取匹配的起止索引(findIndex / findAllIndex);
  • 获取匹配及捕获组内容(findSubmatch / findSubmatchIndex);
  • 全局替换(replaceAll)。

这份测试文件同时被 hangar 测试框架用于生成两类快照:一类是模拟器(sim)目标上的 wing test 运行结果(regex.test.w_test_sim.md),另一类是 tf-aws 目标上的编译产物(regex.test.w_compile_tf-aws.md)。因此,从这份测试用例出发,我们既能学习 API 用法,也能理解 Wing 的测试与快照机制。

正则对象的创建与编译

std.regex 模块对外暴露的核心类型是 Regex,它表示一个已编译的正则表达式模式。在 Wing 中,正则对象只能通过静态工厂方法创建:

let r = regex.compile("p([a-z]+)ch");

regex.compile(pattern: str) 接收一个正则表达式模式字符串,返回一个 Regex 对象。在 SDK 源码中,compile 只是简单地构造内部封装:

// packages/@winglang/sdk/src/std/regex.ts
public static compile(pattern: string): Regex {
  return new Regex(pattern);
}

private constructor(pattern: string) {
  this._regex = new RegExp(pattern);
}

从源码可以看出,Regex 底层直接复用 JavaScript 的 RegExp 引擎,因此 Wing 正则语法与 JavaScript 正则保持一致(支持 [a-z]+、() 捕获组、量词、字符类等标准语法)。也正因如此,Regex 实现了 ILiftable 接口,可以在 preflight(基础设施阶段)与 inflight(运行时阶段)之间安全传递——这在后面“测试中的正则”一节会再次体现。

匹配检测:test 与 expect 断言

创建正则对象后,最基础的操作是判断文本是否匹配。test(text: str): bool 返回布尔值:

let r = regex.compile("p([a-z]+)ch");

// check if there are any matches
expect.equal(r.test("peach"), true);

在 SDK 测试中,expect.equal 来自 Wing 标准库的 expect 模块(API 参考),它用于比较两个值是否相等,并提供包含丰富错误信息的断言报告。这与常规单元测试中的断言函数等价:如果 r.test("peach") 不为 true,测试将失败。

值得注意的是,expect 模块还提供了与正则直接相关的 match 与 doesNotMatch 两个断言函数(expect.match(actual, expected) 检查字符串是否匹配某个正则模式,expect.doesNotMatch 则相反),可以与 Regex.test 结合形成更丰富的测试手段。

查找与索引:find、findIndex 系列

Regex 提供了一组“查找”方法,返回值分为两类:匹配内容本身,以及匹配在文本中的起止索引。

查找单个匹配

// returns the first match, if there is one
expect.equal(r.find("peach peach"), "peach");

// returns the start and end index of the first match, if there is one
expect.equal(r.findIndex("peach punch"), [0, 5]);
  • find(text: str): str? 返回第一个匹配的子串;若没有匹配则返回 nil(可空类型 str?)。
  • findIndex(text: str): MutArray<num>? 返回第一个匹配的 [起始索引, 结束索引],索引从 0 开始,结束索引为开区间(不包含匹配尾字符的位置);若无匹配则返回 nil。

以 r.findIndex("peach punch") 为例,模式 p([a-z]+)ch 匹配到 peach,其位于文本索引 0~5,因此返回 [0, 5]。在 SDK 源码中,findIndex 通过 RegExp.exec 的 result.index 与匹配长度计算:

public findIndex(text: string): number[] | undefined {
  const result = this._regex.exec(text);
  return result ? [result.index, result.index + result[0].length] : undefined;
}

查找所有匹配

// returns all of the non-overlapping matches
expect.equal(r.findAll("peach punch pinch"), ["peach", "punch", "pinch"]);

// returns the start and end index of all matches
expect.equal(r.findAllIndex("peach punch pinch"), [[0, 5], [6, 11], [12, 17]]);
  • findAll(text: str): MutArray<str> 返回所有不重叠匹配的子串数组;没有匹配时返回空数组(源码中通过 matchAll 结合全局正则实现)。
  • findAllIndex(text: str): MutArray<MutArray<num>> 返回每个匹配的 [起始, 结束] 索引数组,同样基于 0 索引。

在 "peach punch pinch" 中,三个匹配 peach、punch、pinch 分别占据 [0,5]、[6,11]、[12,17] 区间,之间没有重叠也没有间隙遗漏。

这里有一个源码层面的实现细节:findAll 与 findAllIndex 内部调用 getGlobalRegex() 辅助方法,为当前正则生成带 g 标志的全局版本,从而借助 String.prototype.matchAll 一次性收集全部匹配:

private getGlobalRegex(): RegExp {
  return this._regex.global ? this._regex : new RegExp(this._regex, "g");
}

捕获组:findSubmatch 与 findSubmatchIndex

当正则中包含 () 捕获组时,除了整体匹配结果,往往还需要提取分组内容。这正是 findSubmatch 系列方法的用途。

// returns the match and all submatches from groups like ([a-z]+)
expect.equal(r.findSubmatch("peach punch"), ["peach", "ea"]);

// returns the start and end index of the match and all submatches
expect.equal(r.findSubmatchIndex("peach punch"), [[0, 5], [1, 3]]);

以模式 p([a-z]+)ch 匹配 "peach punch" 为例:

  • 整体匹配是 peach(索引 0~5);
  • 捕获组 ([a-z]+) 捕获到 ea(索引 1~3)。

因此 findSubmatch 返回 ["peach", "ea"](第一个元素永远是整体匹配,其后依次是各捕获组),findSubmatchIndex 返回 [[0, 5], [1, 3]](外层第一个数组是整体匹配区间,后续数组是各捕获组区间)。

在源码实现中,findSubmatchIndex 使用 exec 返回的捕获组内容,并通过 text.indexOf(submatch, 起始位置) 计算每个捕获组的起止索引:

public findSubmatchIndex(text: string): number[][] | undefined {
  const result = this._regex.exec(text);
  if (!result) {
    return undefined;
  }
  const indices = [[result.index, result.index + result[0].length]];
  result.slice(1).forEach((submatch) => {
    const start = text.indexOf(submatch, indices[indices.length - 1][0]);
    const end = start + submatch.length;
    indices.push([start, end]);
  });
  return indices;
}

需要注意:若无匹配,findSubmatch 与 findSubmatchIndex 均返回 nil(签名分别为 MutArray<str>? 与 MutArray<MutArray<num>>?),而 findAll 系列则返回空数组,两者语义不同。

全局替换:replaceAll

最后一个核心能力是替换。replaceAll(text: str, replacement: str): str 会将文本中所有匹配到的子串替换为指定字符串,并返回新文本:

// replace all occurrences of a match with a string
expect.equal(r.replaceAll("a peach", "<fruit>"), "a <fruit>");

模式 p([a-z]+)ch 在 "a peach" 中匹配到 peach,将其替换为 <fruit>,得到 "a <fruit>"。该方法的源码实现同样依赖全局正则:

public replaceAll(text: string, replacement: string): string {
  const globalRegex = this.getGlobalRegex();
  return text.replace(globalRegex, replacement);
}

在测试块中封装正则用例

SDK 测试文件的第二部分将同样的断言封装进 test "regex" { ... } 测试块中,这也是 Wing 中组织测试的标准方式:

test "regex" {
  let r = regex.compile("p([a-z]+)ch");

  expect.equal(r.test("peach"), true);
  expect.equal(r.find("peach peach"), "peach");
  expect.equal(r.findAll("peach punch pinch"), ["peach", "punch", "pinch"]);
  expect.equal(r.findIndex("peach punch"), [0, 5]);
  expect.equal(r.findAllIndex("peach punch pinch"), [[0, 5], [6, 11], [12, 17]]);
  expect.equal(r.findSubmatch("peach punch"), ["peach", "ea"]);
  expect.equal(r.findSubmatchIndex("peach punch"), [[0, 5], [1, 3]]);
  expect.equal(r.replaceAll("a peach", "<fruit>"), "a <fruit>");
}

这个测试块覆盖了 std.regex 的全部 8 个方法,形成了一份可独立运行、可直接套用到自己项目中的完整测试模板。从 Wing 项目模板(如 empty 模板)可以看到,bring expect; 与 test "..." { ... } 是 Wing 单元测试的标准组合:前者引入断言库,后者声明一个可被测试运行器识别的测试用例。

快照解析:hangar 如何验证 regex 测试

tools/hangar/__snapshots__/test_corpus/sdk_tests/std/ 目录下与 regex.test.w 对应着两份快照文件,分别代表两个验证维度。

sim 目标运行结果快照

regex.test.w_test_sim.md 记录了在模拟器(sim)目标上执行 wing test 的输出:

pass ─ regex.test.wsim » root/Default/test:regex

Tests 1 passed (1)
Snapshots 1 skipped
Test Files 1 passed (1)
Duration <DURATION>

这份快照表明:测试文件中的 test "regex" 测试块在模拟器环境全部通过(Tests 1 passed (1)),文件级结果为 Test Files 1 passed (1)。Duration <DURATION> 中的占位符是 hangar 刻意替换掉时间戳,以保证快照的确定性——这正是快照测试的核心价值:运行结果必须可重复、可对比。

tf-aws 目标编译快照

regex.test.w_compile_tf-aws.md 则记录了将同一测试文件编译到 tf-aws 目标时生成的 Terraform 配置:

{
  "//": {
    "metadata": {
      "backend": "local",
      "stackName": "root"
    },
    "outputs": {}
  },
  "provider": {
    "aws": [
      {}
    ]
  }
}

因为 regex.test.w 只包含纯字符串操作与测试断言,没有声明任何云资源(如 cloud.Bucket、cloud.Function 等),所以编译产物中只有 AWS provider 的空壳配置,没有实际的资源定义。这从侧面印证了:std.regex 是纯运行时能力,不涉及基础设施编排。

快照的生成机制

这些快照由 hangar 测试框架自动生成。查看 generate_tests.ts 可以发现,hangar 会遍历 sdk_tests 目录下所有 .w 文件,为每个文件生成两组 vitest 用例:一组执行 wing compile -t tf-aws(编译快照),另一组执行 wing test -t sim(运行快照),产物统一写入 __snapshots__ 目录:

test("wing compile -t tf-aws", async () => {
  await compileTest(sourceDir, filename, env, includeJavaScriptInSnapshots, skipMarkdownSnapshot, args);
});

test("wing test -t sim", async () => {
  await testTest(sourceDir, filename, env, skipMarkdownSnapshot);
});

因此,当你看到 regex.test.w_test_sim.md 与 regex.test.w_compile_tf-aws.md 时,它们分别代表的是“该测试在 sim 模拟器上的通过记录”与“该测试在 tf-aws 目标上的编译产物”,这是 Wing 项目质量保障体系中针对 SDK 行为测试的双重验证。

本地运行与验证

如果你想在自己机器上复现上述正则测试,可以按以下步骤操作:

  1. 进入仓库根目录后,先安装依赖并构建 SDK(hangar 依赖已编译产物运行测试):
    pnpm install
    pnpm build
    
  2. 直接对测试文件执行模拟器测试:
    cd packages/winglang && npx wing test ../../tests/sdk_tests/std/regex.test.w -t sim
    
    或在仓库根目录通过 turbo 运行 SDK 测试集:
    npx turbo run test --filter=@winglang/sdk
    
  3. 观察输出,若所有断言成立,你会看到类似快照中的 Tests 1 passed (1) 结果。

此外,Wing 官方文档的 by-example 正则示例 提供了同一个正则模式的另一种演示形式——使用 log 输出结果(其中 replaceAll("a peach", "<fruit>") 的输出为 a <fruit>),并且可以通过 wing it 在 Wing Console 中交互式查看运行结果,适合作为学习阶段的直观参考。

小结

通过 tests/sdk_tests/std/regex.test.w 及其 hangar 快照,我们完整梳理了 Wing 标准库 std.regex 的能力边界与使用方式:

  • 创建:regex.compile(pattern) 编译模式,底层复用 JavaScript RegExp,并通过 ILiftable 支持跨阶段传递;
  • 检测:test 返回布尔匹配结果,可配合 expect 模块的 equal / match 断言使用;
  • 查找:find / findAll 返回匹配内容,findIndex / findAllIndex 返回 0 基起止索引;
  • 捕获组:findSubmatch / findSubmatchIndex 同时返回整体匹配与各分组内容(含索引);
  • 替换:replaceAll 基于全局正则完成全部替换;
  • 验证:hangar 框架通过 sim 运行快照与 tf-aws 编译快照双重保障 API 行为正确,且快照中 <DURATION> 占位符保证了结果可确定性对比。

无论你是在编写单元测试、处理日志文本,还是构建需要字符串模式匹配的云应用,std.regex 这套 API 都能覆盖主流需求,并且可以直接将 regex.test.w 作为可复用的测试模板。

登录后查看全文
wing