创建包含正则表达式匹配中所有组的数组的有效解决方案

Effective solution for create array containing all groups in regex matches

本文关键字:数组 有效 解决方案 正则表达式 包含 创建      更新时间:2023-09-26

我正在寻找一种有效的方法来创建包含所有匹配项的数组,其中包含正则表达式组匹配项。

例如,正则表达式/(1)(2)(3)/g字符串123预期结果['1','2','3']

我当前的代码如下所示:

    var matches = [];
    value.replace(fPattern, function (a, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15) {
        for(var i = 1, v; i < 15; i++){
            v = eval('s' + i);
            if(v){
                matches.push(v);       
            }else{
                break;
            }                
        }
    });

有效,但我不喜欢它的方式。

第一件事是我实际上不知道我的正则表达式变量中会有多少组fPattern所以我需要定义很多不必要的变量s1, s2 ... etc

第二个问题是我决定使用邪恶eval来防止将这些变量"手动"一一推送到数组中,也许有更好的解决方案?

还有一件事 - 我确实尝试使用match()但不幸的是,当我有模式/(1)(2)(3)/g时它会返回我数组['123']所以这不是我想要实现的。

谢谢!

编辑

好的,我找到了一些看起来更好的东西

    matches = fPattern.exec(value);        
    if(matches && matches.length){
        for(var key in matches){                                
            if(key !== '0'){
                if(key !== 'index'){
                    formated += matches[key] + ' ';       
                }else{
                    break;
                }                    
            }                
        };
    }

类似

arrays = "123".match(/(1)(2)(3)/);
arrays.splice(0,1);
console.log(arrays);
=> Array [ "1", "2", "3" ]

match返回一个数组,其中数组索引0将包含整个匹配项。从数组索引1开始,它将包含相应捕获组的值。

arrays.splice(0,1);

将从数组中删除索引0元素,整个匹配项,生成的数组将仅包含捕获组值

使用 RegExp.exec 并收集其返回值,这些返回值由主匹配项、捕获组和主匹配项的起始索引组成。

function findall(re, input) {
    // Match only once for non global regex
    // You are free to modify the code to turn on the global flag
    // and turn it off before return
    if (!re.global) {
        return input.match(re);
    } else {
        re.lastIndex = 0;
    }
    var arr;
    var out = [];
    while ((arr = re.exec(input)) != null) {
        delete arr.input; // Don't need this
        out.push(arr);
        // Empty string match. Need to advance lastIndex
        if (arr[0].length == 0) {
            re.lastIndex++;
        }
    }
    return out;
}

一个状态较少/功能更强大的解决方案可能是这样的:

function findInString(string, pattern) {
   return string.split('').filter(function (element) {
      return element.match(pattern)
   })
}

接受字符串以搜索和正则表达式文本,返回匹配元素的数组。因此,例如:

var foo = '123asfasff111f6';
findInString(foo, /'d/g)

将返回[ '1', '2', '3', '1', '1', '1', '6' ],这似乎是您要查找的(?(至少,基于以下内容)

例如正则表达式/(1)(2)(3)/g 字符串 123 预期结果 ['1', '2', '3']

您可以传入所需的任何正则表达式文本,它应该作用于数组中的每个项目,如果匹配,则返回它。如果您想轻松推理状态/以后可能必须重用它以匹配不同的模式,我会选择这样的东西。这个问题对我来说有点模糊,所以你的确切需求可能略有不同——试图偏离你的预期输入和输出。