[英]RegExp capturing group in capturing group
I want to capture the "1" and "2" in " http://test.com/1/2 ". 我想捕获“ http://test.com/1/2 ”中的“ 1”和“ 2”。 Here is my regexp
/(?:\\/([0-9]+))/g
. 这是我的正则表达式
/(?:\\/([0-9]+))/g
。 The problem is that I only get ["/1", "/2"]
. 问题是我只得到
["/1", "/2"]
。 According to http://regex101.com/r/uC2bW5 I have to get "1" and "1". 根据http://regex101.com/r/uC2bW5,我必须获取“ 1”和“ 1”。
I'm running my RegExp in JS. 我正在JS中运行RegExp。
You have a couple of options: 您有两种选择:
Use a while
loop over RegExp.prototype.exec
: 在
RegExp.prototype.exec
使用while
循环:
var regex = /(?:\\/([0-9]+))/g, string = "http://test.com/1/2", matches = []; while (match = regex.exec(string)) { matches.push(match[1]); }
Use replace
as suggested by elclanrs : 根据elclanrs的建议使用
replace
:
var regex = /(?:\\/([0-9]+))/g, string = "http://test.com/1/2", matches = []; string.replace(regex, function() { matches.push(arguments[1]); });
In Javascript your "match" has always an element with index 0
, that contains the WHOLE pattern match. 在Javascript中,您的“匹配”始终具有索引为
0
的元素,其中包含整个模式匹配。 So in your case, this index 0 is /1
and /2
for the second match. 因此,在您的情况下,第二个匹配的索引0为
/1
和/2
。
If you want to get your DEFINED first Matchgroup (the one that does not include the /
), you'll find it inside the Match-Array Entry with index 1
. 如果要获得定义的第一个匹配组(不包含
/
的匹配组),则可以在索引为1
的匹配数组项中找到它。
This index 0
cannot be removed and has nothing to do with the outer matching group you defined as non-matching
by using ?:
不能删除该索引
0
,它与使用?:
定义为non-matching
的外部匹配组无关?:
Imagine Javascript wrapps your whole regex into an additional set of brackets. 想象一下Javascript将您的整个正则表达式包装在另外一组括号中。
Ie the String Hello World
and the Regex /Hell(o) World/
will result in : 即字符串
Hello World
和Regex /Hell(o) World/
将导致:
[0 => Hello World, 1 => o]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.