Javascript Regex - Find all possible matches, even in already captured matches

后端 未结 3 1592
余生分开走
余生分开走 2020-12-03 14:26

I\'m trying to obtain all possible matches from a string using regex with javascript. It appears that my method of doing this is not matching parts of the string

3条回答
  •  清歌不尽
    2020-12-03 15:02

    Unfortunately, it's not quite as simple as a single string.match.

    The reason is that you want overlapping matches, which the /g flag doesn't give you.

    You could use lookahead:

    var re = /A\d+B\d+Y(?=:A\d+B\d+Y)/g;
    

    But now you get:

    string.match(re); // ["A1B1Y", "A1B2Y", "A1B5Y", "A1B6Y", "A1B9Y", "A1B10Y"]
    

    The reason is that lookahead is zero-width, meaning that it just says whether the pattern comes after what you're trying to match or not; it doesn't include it in the match.

    You could use exec to try and grab what you want. If a regex has the /g flag, you can run exec repeatedly to get all the matches:

    // using re from above to get the overlapping matches
    
    var m;
    var matches = [];
    var re2 = /A\d+B\d+Y:A\d+B\d+Y/g; // make another regex to get what we need
    
    while ((m = re.exec(string)) !== null) {
      // m is a match object, which has the index of the current match
      matches.push(string.substring(m.index).match(re2)[0]);
    }
    
    matches == [
      "A1B1Y:A1B2Y", 
      "A1B2Y:A1B3Y", 
      "A1B5Y:A1B6Y", 
      "A1B6Y:A1B7Y", 
      "A1B9Y:A1B10Y", 
      "A1B10Y:A1B11Y"
    ];
    

    Here's a fiddle of this in action. Open up the console to see the results

    Alternatively, you could split the original string on :, then loop through the resulting array, pulling out the the ones that match when array[i] and array[i+1] both match like you want.

提交回复
热议问题