You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何捕获被另一模式包裹的所有匹配子模式?

解决被"aa"包裹的数字全捕获问题

问题原因

你使用的正则/aa(\d)*?aa/ig中,(\d)*?是重复匹配单个数字,但捕获组重复匹配时会覆盖之前的结果,最终仅保留最后一次匹配的数字5,这就是为什么你只得到单个捕获值。

解决方案

方案一:先提取完整数字串再拆分(符合你的期望输出结构)

先匹配整个aa...aa片段并捕获中间的数字序列,再将序列拆分为单个数字,最后构造你需要的结果结构:

const str = "aa12345aa";
const fullMatch = str.match(/aa(\d+)aa/i);

if (fullMatch) {
  // 将捕获的数字串拆分为单个数字数组
  const individualDigits = fullMatch[1].split('');
  // 构造目标结果数组
  const result = [fullMatch[0], ...individualDigits];
  // 保留原匹配的元数据属性
  result.index = fullMatch.index;
  result.input = fullMatch.input;
  result.groups = fullMatch.groups;
  
  console.log(result);
}

执行结果:

['aa12345aa', '1', '2', '3', '4', '5', index: 0, input: 'aa12345aa', groups: undefined]

方案二:直接匹配所有单个数字(仅获取数字)

如果只需要提取被aa包裹的所有数字,可使用前后断言直接匹配每个数字:

const str = "aa12345aa";
const digits = Array.from(str.matchAll(/(?<=aa)\d(?=aa)/g), match => match[0]);

console.log(digits); // ['1','2','3','4','5']

关键说明

正则表达式的捕获组不支持重复捕获并保留所有结果,因此必须通过“先捕获完整序列再拆分”或“单独匹配每个目标元素”的方式实现需求。

内容的提问来源于stack exchange,提问作者KaraNoKara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:22:47