简体   繁体   English

仅从Javascript中捕获正则表达式的括号中获取内容

[英]Get only contents from capturing parenthesis of a Regular Expression in Javascript

Why does 为什么

"$1 $2 $3".match(/\$(\d+)/g)

return 返回

 ["$1", "$2", "$2"]

, not 不是

 ["1", "2", "3"]

?

If I remove the global flag, it will give me the match and the captured match: 如果我删除全局标志,它将给我匹配和捕获的匹配:

["$1", "1"]

but only one. 但只有一个。

Is there a way to do a reg ex capture to not give me this? 有没有办法做一个reg ex捕获不给我这个?

Even putting in a non-capturing parentheses around the $ gives me the same results, eg: 即使在$周围放置一个非捕获括号也会给出相同的结果,例如:

"$1 $2 $3".match(/(?:\$)(\d+)/g)

If you use a capturing group in your regex (eg parens), then you can't get multiple matches with the g flag the way you are trying to do it because the .match() function can't return two dimensions of data (a list of capturing groups for each time it matched). 如果你在你的正则表达式中使用一个捕获组(例如parens),那么就不能像你尝试这样做那样使用g标志进行多次匹配,因为.match()函数不能返回两维数据(每次匹配时的捕获组列表)。 It could have been designed to do that, but it wasn't so in order to get that info, you have to loop and call .exec() multiple times where you get all the data from each successive match each time you call it. 它本来可以设计用来做到这一点,但事实并非如此,为了得到这些信息,你必须循环并多次调用.exec() ,每次你调用它时,每次连续匹配都会获得所有数据。

Getting this data using .exec() looks like this: 使用.exec()获取此数据如下所示:

var str = "$1 $2 $3", matches;
var allMatches = [];
var reg = /\$(\d+)/g;

while (matches = reg.exec(str)) {
    // matches[1] is each successive match here from your captured group
    allMatches.push(matches[1]);
}
// allMatches will be what you wanted ["1", "2", "3"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM