问题
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 this 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 there's something I'm missing with the capture group and/or $
logic. Any help would be appreciated. (I know I can figure out how to do this in multiple regular expressions, but I want to understand what is happening here.)
回答1:
Yes, that’s exactly what it does; you’re not doing anything wrong. When a group is given a quantifier, it only captures its last match, and that’s all it will ever do in JavaScript. The general fix is to use multiple regular expressions, as you said, e.g.
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
来源:https://stackoverflow.com/questions/27111898/why-is-my-regex-capture-group-only-capturing-the-last-part-of-the-string-when-it