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

北慕城南 提交于 2020-01-03 18:57:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!