使用JS正则获取字符串中全部的特定匹配项(分组)

 

。。

 示例:

const str = 'bedab1cvhuab2ikmab3ng';
const reg = /ab(\d+)/g;
const ans = [];
let matched = null;
while ((matched = reg.exec(str)) !== null) {
    console.log(matched);
    ans.push(matched[1]);
}

// output:
// [
//   'ab1',
//   '1',
//   index: 3,
//   input: 'bedab1cvhuab2ikmab3ng',
//   groups: undefined
// ]
//
// [
//   'ab2',
//   '2',
//   index: 10,
//   input: 'bedab1cvhuab2ikmab3ng',
//   groups: undefined
// ]
// 
// [
//   'ab3',
//   '3',
//   index: 16,
//   input: 'bedab1cvhuab2ikmab3ng',
//   groups: undefined
// ]

console.log(ans);
// [ '1', '2', '3' ]

:要获取到全部的匹配项,相应的正则中一定要有 'g' 修饰符

posted @ 2022-08-15 09:57  樊顺  阅读(2515)  评论(0)    收藏  举报