RegEx to extract all matches from string using RegExp.exec

前端 未结 17 1144
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:49

I\'m trying to parse the following kind of string:

[key:\"val\" key2:\"val2\"]

where there are arbitrary key:\"val\" pairs inside. I want t

17条回答
  •  孤街浪徒
    2020-11-22 03:27

    Here is my function to get the matches :

    function getAllMatches(regex, text) {
        if (regex.constructor !== RegExp) {
            throw new Error('not RegExp');
        }
    
        var res = [];
        var match = null;
    
        if (regex.global) {
            while (match = regex.exec(text)) {
                res.push(match);
            }
        }
        else {
            if (match = regex.exec(text)) {
                res.push(match);
            }
        }
    
        return res;
    }
    
    // Example:
    
    var regex = /abc|def|ghi/g;
    var res = getAllMatches(regex, 'abcdefghi');
    
    res.forEach(function (item) {
        console.log(item[0]);
    });
    

提交回复
热议问题