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

JavaScript正则仅提取括号内匹配内容至数组的方法

解决方案

当正则带有g全局标志时,match()方法只会返回所有完整匹配的结果,不会单独提取捕获组内容。要只收集括号内的捕获内容,可以用以下两种方法:

方法一:循环调用RegExp.exec()

带g标志的正则,每次调用exec()会返回当前匹配的详细结果(包括捕获组),并移动匹配指针到下一个位置,循环执行直到返回null即可收集所有捕获组内容:

var myString = "unimportant:part.one:unimportant:part.two:unimportant:part.three";
// 注意:原正则中的.需要转义为\.,否则会匹配任意字符,修正后的正则
var regex = /\w*:(part\.\w*)./gi;
var myArray = [];
let matchResult;

while ((matchResult = regex.exec(myString)) !== null) {
  // matchResult[1]就是括号内捕获的内容
  myArray.push(matchResult[1]);
}

console.log(myArray); // 输出:["part.one", "part.two", "part.three"]

方法二:利用String.replace()的回调函数

replace()方法会遍历所有匹配项,通过回调函数可以获取每个匹配的捕获组内容,借此收集到数组中(无需修改原字符串):

var myString = "unimportant:part.one:unimportant:part.two:unimportant:part.three";
var regex = /\w*:(part\.\w*)./gi;
var myArray = [];

myString.replace(regex, function(_, captured) {
  // captured 参数对应第一个捕获组的内容
  myArray.push(captured);
});

console.log(myArray); // 输出:["part.one", "part.two", "part.three"]

额外提示

原正则中的.是元字符,会匹配任意单个字符,如果你的目标是匹配字面量的点符号,必须转义为\.,否则可能会出现不符合预期的匹配结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:40:32