javascript - 我想获得与正则表达式的所有匹配项。 Javascript

标签 javascript regex match combinations

对不起我的英语。

var r=/([a-z]*)[a]{1}([a-z]*)/igm;
var s="araba";

我需要的结果,

a raba index:0
ar a ba index:2
arab a index:4

我怎样才能用正则表达式做到这一点?

最佳答案

单个正则表达式调用将无法实现,因为正则表达式在匹配某些内容后无法返回。您必须制作一个正则表达式来查找您想要的字符集(在您的示例中 [a])并在每次匹配时停止,生成一个新结果并将其插入数组(或直接使用)。 RegExp.prototype.exec 是这样需要的:

function mySplit(str, charList) {
    // regex will match any character provided in the charList string (no need for {1} as it is the default)
    var regex = new RegExp("[" + charList + "]", "g");
    // the result array, will contain object indecating where the match was found and the parts
    var result = [];
    
    // before starting, execute the regex on the string str
    regex.exec(str);
    // using do-while to guarantee that there will be at least one result in the result array
    do {
        // the index of this match
        var index = regex.lastIndex - 1;
        
        // the result object for this match
        var r = {
            index: index,              // the index
            parts: []                  // the parts (for example "a", "raba" ...)
        };
        
        var p;
        // PREFIX PART
        p = str.substr(0, index);      // get the prefix
        if(p.length) r.parts.push(p);  // if not empty push it
        // THE CHARACTER
        p = str.substr(index, 1);      // get it
        if(p.length) r.parts.push(p);  // if not empty push it (this is could be empty if nothing is matched)
        // POSTFIX PART
        p = str.substr(index + 1);     // get it
        if(p.length) r.parts.push(p);  // push it if not empty
        
        result.push(r);                // push the object r as a result
    } while(regex.exec(str));
    
    return result;
}

console.log(mySplit("araba", "a"));

注意: mySplit 的第二个参数可以是你想要的任意多个字母。例如 mySplit("araba", "ab"); 将返回:

[
    {
        "index": 0,
        "parts": [
            "a",
            "raba"
        ]
    },
    {
        "index": 2,
        "parts": [
            "ar",
            "a",
            "ba"
        ]
    },
    {
        "index": 3,
        "parts": [
            "ara",
            "b",
            "a"
        ]
    },
    {
        "index": 4,
        "parts": [
            "arab",
            "a"
        ]
    }
]

关于javascript - 我想获得与正则表达式的所有匹配项。 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42776590/

相关文章:

javascript - 嵌入式对象——对象中的对象

javascript - 将不存在的日期数据添加到 JSON

javascript - 如何更快地对 HTML 表格进行排序?

regex - HAProxy 删除尾部斜杠

ruby - 使用正则表达式扫描子字符串并忽略大小写

Java 正则表达式 : Match text between two strings with boundary conditions

elasticsearch - 无法为 ElasticSearch 编写通配符查询?

javascript - 我如何添加类名正文向下滚动 react ?

正则表达式在连字符前后获取文本

ruby - 不同 Ruby 版本的 `scan` 和 `match` 行为存在差异