How can I match overlapping strings with regex?

后端 未结 6 1739
猫巷女王i
猫巷女王i 2020-11-22 03:27

Let\'s say I have the string

\"12345\"

If I .match(/\\d{3}/g), I only get one match, \"123\". Why don\'t I get

6条回答
  •  盖世英雄少女心
    2020-11-22 03:28

    You can't do this with a regex alone, but you can get pretty close:

    var pat = /(?=(\d{3}))\d/g;
    var results = [];
    var match;
    
    while ( (match = pat.exec( '1234567' ) ) != null ) { 
      results.push( match[1] );
    }
    
    console.log(results);

    In other words, you capture all three digits inside the lookahead, then go back and match one character in the normal way just to advance the match position. It doesn't matter how you consume that character; . works just as well \d. And if you're really feeling adventurous, you can use just the lookahead and let JavaScript handle the bump-along.

    This code is adapted from this answer. I would have flagged this question as a duplicate of that one, but the OP accepted another, lesser answer.

提交回复
热议问题