如何使用javascript正则表达式多次捕获多个组

时间:2015-08-01 22:36:05

标签: javascript regex

我有这段代码片段旨在从github api中提取下一个和最后一个链接值...

var types = {},
    str = '<https://api.github.com/repositories/1424470/issues?access_token=f554f90b4c95c78091a4202150d4583082dab1ce&page=2>; rel="next", <https://api.github.com/repositories/1424470/issues?access_token=f554f90b4c95c78091a4202150d4583082dab1ce&page=7>; rel="last"',
    rex = /\s*<https?:\/\/api.github.com\/.+?&page=(\d+)>;\s*rel="(\w+?)"(?:,|$)/g;

// use regex replace method to capture multiple groups multiple times
str.replace(rex, function(_, page, type){
    types[type] = +page;
});

console.log(types);
// {next: 2, last: 7}

它运行正常,但感觉就像是误用了正则表达式替换方法,我没有返回任何东西,而是仅仅为了每次匹配都有回调而使用它,我用来建立输出对象

我更喜欢某种matchAll,返回多维匹配数组和部分。

在javascript中有更好的方法来处理这种情况吗?

1 个答案:

答案 0 :(得分:1)

您可以在循环中使用exec()方法,将匹配结果推送到多维数组。

function find_all(re, s) {
   var types = [];
   while (m = re.exec(s)) {
        types.push([m[2], m[1]])
   }
   return types;
}

var regex = new RegExp('<https?://[^>]+page=(\\d+)>;\\s*rel="([^"]+)"', 'gi');

find_all(regex, str) //=> [ [ 'next', '2' ], [ 'last', '7' ] ]