为什么我的正则表达式捕获组仅在匹配多个部分时捕获字符串的最后部分? [英] Why is my regex capture group only capturing the last part of the string when it matches multiple parts?

查看:259
本文介绍了为什么我的正则表达式捕获组仅在匹配多个部分时捕获字符串的最后部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);

我做了一个 JSFiddle

变量匹配应该成为这个数组:

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"
]



我的想法



我的猜测是捕捉组和/或<$ c我都缺少一些东西$ c> $ 逻辑。任何帮助,将不胜感激。 (我知道我可以弄清楚如何在多个正则表达式中执行此操作,但我想了解这里发生了什么。)

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.)

推荐答案

<是的,这正是它的作用;你没有做错任何事。当一个组被赋予量词时,它只捕获它的最后一个匹配,这就是它在JavaScript中所做的一切。一般的解决方法是使用多个正则表达式,如你所说,例如。

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

这篇关于为什么我的正则表达式捕获组仅在匹配多个部分时捕获字符串的最后部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆