Why does my regex capture group only capture the last part of a string when it matches multiple parts?

What i tried

var test = "asdfdas ABCD EFGH";
var regex = /^\S+( [A-Z]{4})+$/; 
    // Also tried: /^\S+( [A-Z]{4})+$/g
    // And: /^\S+( [A-Z]{4})+?$/g
var matches = test.match(regex);

      

I made a JSFiddle .

What i expect

The variable matches

should become the following array:

[
  "asdfdas ABCD EFGH",
  " ABCD",
  " EFGH"
]

      

What i get

The variable matches

is actually this array:

[
  "asdfdas ABCD EFGH",
  " EFGH"
]

      

My thoughts

My guess is that I am missing a capture group and / or $

. Any help would be greatly appreciated. (I know I can figure out how to do this in multiple regexes, but I want to understand what's going on here.)

+3


source to share


1 answer


Yes, that's exactly what he does; you're not doing anything wrong. When a quantifier is given to a group, it only captures its last match, and that's all it will ever do in JavaScript. The general fix is ​​to use multiple regex as you said, for example



var test = "asdfdas ABCD EFGH";
var match = test.match(/^\S+((?: [A-Z]{4})+)$/); // capture all repetitions
var matches = match[1].match(/ [A-Z]{4}/g); // match again to get individual ones
      

+2


source







All Articles