Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 捕获组中的RegExp捕获组_Javascript_Regex - Fatal编程技术网

Javascript 捕获组中的RegExp捕获组

Javascript 捕获组中的RegExp捕获组,javascript,regex,Javascript,Regex,我想捕获“”中的“1”和“2”。这是我的regexp/(?:\/([0-9]+)/g。 问题是我只得到[“/1”、“/2”]。根据我的经验,我必须得到“1”和“1” 我正在JS中运行我的RegExp。在Javascript中,您的“匹配”总是有一个索引为0的元素,它包含整个模式匹配。因此,在您的情况下,对于第二个匹配,索引0是/1,而/2 如果要获取定义的第一个匹配组(不包括/),可以在索引为1的匹配数组条目中找到它 此索引0无法删除,并且与您使用?:定义为不匹配的外部匹配组无关 想象一下Jav

我想捕获“”中的“1”和“2”。这是我的regexp
/(?:\/([0-9]+)/g
。 问题是我只得到
[“/1”、“/2”]
。根据我的经验,我必须得到“1”和“1”

我正在JS中运行我的RegExp。

在Javascript中,您的“匹配”总是有一个索引为
0
的元素,它包含整个模式匹配。因此,在您的情况下,对于第二个匹配,索引0是
/1
,而
/2

如果要获取定义的第一个匹配组(不包括
/
),可以在索引为
1
的匹配数组条目中找到它

此索引
0
无法删除,并且与您使用
?:
定义为
不匹配的外部匹配组无关

想象一下Javascript将整个正则表达式包装到一组附加的括号中

也就是说,字符串
Hello World
和正则表达式
/Hell(o)World/
将导致:

[0 => Hello World, 1 => o]

您有两个选择:

  • 使用
    while
    循环
    RegExp.prototype.exec

    var regex = /(?:\/([0-9]+))/g,
        string = "http://test.com/1/2",
        matches = [];
    
    while (match = regex.exec(string)) {
        matches.push(match[1]);
    }
    
  • 按照以下建议使用
    替换


  • 那么你是如何在JS中使用它的呢?我怀疑您使用的
    match
    是错误的……在这里,使用这个伟大的函数@elclanrsI认为match将返回所有匹配组,而不使用while循环。
    var regex = /(?:\/([0-9]+))/g,
        string = "http://test.com/1/2",
        matches = [];
    
    string.replace(regex, function() {
        matches.push(arguments[1]);
    });