如何在具有多个匹配项的 JavaScript RegEx 中仅返回捕获的组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22581979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:24:47  来源:igfitidea点击:

How to return only captured groups in a JavaScript RegEx with multiple matches

javascriptregex

提问by swider

Simplified example:

简化示例:

/not(?:this|that)(.*?)end/ig.exec('notthis123end notthat45end')

/not(?:this|that)(.*?)end/ig.exec('notthis123end notthat45end')

returns

回报

["notthis123end", "123"]

["notthis123end", "123"]

I'm shooting for

我正在为

["123", "45"]

["123", "45"]

All I've figured out is putting the RE in a RegExpobject and running a while loop around the exec, which seems kinda silly, or using match, but getting back the entire match, not just the captured part.

我所想到的只是将 RE 放在一个RegExp对象中并在 周围运行 while 循环exec,这看起来有点傻,或者使用match,但要取回整个匹配项,而不仅仅是捕获的部分。

回答by thefourtheye

Your RegEx seems to be working fine. Problem is with the interpretation of the output.

您的 RegEx 似乎工作正常。问题在于输出的解释。

  1. To get multiple matches of the RegEx, you should do, something like this

    var regEx = /not(?:this|that)(.*?)end/ig;
    var data  = "notthis123end notthat45end";
    var match = regEx.exec(data);
    
    while(match !== null) {
        console.log(match[1]);
        match = regEx.exec(data);
    }
    

    Note:It is important to store the RegEx in a variable like this and use a loop with that. Because, to get the multiple matches, JavaScript RegEx implementation, stores the current index of the match in the RegEx object itself. So, next time execis called it picks up from where it left of. If we use RegEx literal as it is, then we ll end up in infinite loop, as it will start from the beginning always.

  2. The result of execmethod has to be interpreted like this, the first value is the entire match and the next element onwards we get the groups inside the matches. In this RegEx, we have only one group. So, we access that with match[1].

  1. 要获得 RegEx 的多个匹配项,您应该这样做,就像这样

    var regEx = /not(?:this|that)(.*?)end/ig;
    var data  = "notthis123end notthat45end";
    var match = regEx.exec(data);
    
    while(match !== null) {
        console.log(match[1]);
        match = regEx.exec(data);
    }
    

    注意:将 RegEx 存储在这样的变量中并使用循环很重要。因为,为了获得多个匹配项,JavaScript RegEx 实现将匹配项的当前索引存储在 RegEx 对象本身中。所以,下一次exec被称为它从它离开的地方开始。如果我们按原样使用 RegEx 文字,那么我们最终会陷入无限循环,因为它总是从头开始。

  2. 方法的结果exec必须像这样解释,第一个值是整个匹配项,下一个元素是匹配项中的组。在这个 RegEx 中,我们只有一个组。因此,我们使用match[1].