gpt4 book ai didi

javascript - 捕获组中的 RegExp 捕获组

转载 作者:行者123 更新时间:2023-11-28 01:14:08 25 4
gpt4 key购买 nike

我想捕获“http://test.com/1/2”中的“1”和“2”。这是我的正则表达式 /(?:\/([0-9]+))/g。问题是我只得到 ["/1", "/2"]。根据http://regex101.com/r/uC2bW5我必须得到“1”和“1”。

我正在 JS 中运行我的 RegExp。

最佳答案

您有几个选择:

  1. 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]);
    }
  2. 按照elclanrs的建议使用replace :

    var regex = /(?:\/([0-9]+))/g,
    string = "http://test.com/1/2",
    matches = [];

    string.replace(regex, function() {
    matches.push(arguments[1]);
    });

关于javascript - 捕获组中的 RegExp 捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24048286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com