RegEx to extract all matches from string using RegExp.exec

前端 未结 17 1172
-上瘾入骨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:09

    Use this...

    var all_matches = your_string.match(re);
    console.log(all_matches)
    

    It will return an array of all matches...That would work just fine.... But remember it won't take groups in account..It will just return the full matches...

    0 讨论(0)
  • 2020-11-22 03:11

    Based on Agus's function, but I prefer return just the match values:

    var bob = "> bob <";
    function matchAll(str, regex) {
        var res = [];
        var m;
        if (regex.global) {
            while (m = regex.exec(str)) {
                res.push(m[1]);
            }
        } else {
            if (m = regex.exec(str)) {
                res.push(m[1]);
            }
        }
        return res;
    }
    var Amatch = matchAll(bob, /(&.*?;)/g);
    console.log(Amatch);  // yeilds: [>, <]
    
    0 讨论(0)
  • 2020-11-22 03:12

    Iterables are nicer:

    const matches = (text, pattern) => ({
      [Symbol.iterator]: function * () {
        const clone = new RegExp(pattern.source, pattern.flags);
        let match = null;
        do {
          match = clone.exec(text);
          if (match) {
            yield match;
          }
        } while (match);
      }
    });
    

    Usage in a loop:

    for (const match of matches('abcdefabcdef', /ab/g)) {
      console.log(match);
    }
    

    Or if you want an array:

    [ ...matches('abcdefabcdef', /ab/g) ]
    
    0 讨论(0)
  • 2020-11-22 03:18

    I would definatly recommend using the String.match() function, and creating a relevant RegEx for it. My example is with a list of strings, which is often necessary when scanning user inputs for keywords and phrases.

        // 1) Define keywords
        var keywords = ['apple', 'orange', 'banana'];
    
        // 2) Create regex, pass "i" for case-insensitive and "g" for global search
        regex = new RegExp("(" + keywords.join('|') + ")", "ig");
        => /(apple|orange|banana)/gi
    
        // 3) Match it against any string to get all matches 
        "Test string for ORANGE's or apples were mentioned".match(regex);
        => ["ORANGE", "apple"]
    

    Hope this helps!

    0 讨论(0)
  • 2020-11-22 03:19

    To loop through all matches, you can use the replace function:

    var re = /\s*([^[:]+):\"([^"]+)"/g;
    var s = '[description:"aoeu" uuid:"123sth"]';
    
    s.replace(re, function(match, g1, g2) { console.log(g1, g2); });
    
    0 讨论(0)
  • 2020-11-22 03:21

    We are finally beginning to see a built-in matchAll function, see here for the description and compatibility table. It looks like as of May 2020, Chrome, Edge, Firefox, and Node.js (12+) are supported but not IE, Safari, and Opera. Seems like it was drafted in December 2018 so give it some time to reach all browsers, but I trust it will get there.

    The built-in matchAll function is nice because it returns an iterable. It also returns capturing groups for every match! So you can do things like

    // get the letters before and after "o"
    let matches = "stackoverflow".matchAll(/(\w)o(\w)/g);
    
    for (match of matches) {
        console.log("letter before:" + match[1]);
        console.log("letter after:" + match[2]);
    }
    
    arrayOfAllMatches = [...matches]; // you can also turn the iterable into an array
    

    It also seem like every match object uses the same format as match(). So each object is an array of the match and capturing groups, along with three additional properties index, input, and groups. So it looks like:

    [<match>, <group1>, <group2>, ..., index: <match offset>, input: <original string>, groups: <named capture groups>]
    

    For more information about matchAll there is also a Google developers page. There are also polyfills/shims available.

    0 讨论(0)
提交回复
热议问题