Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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
如何使用带有';g';JavaScript中的选项_Javascript_Regex - Fatal编程技术网

如何使用带有';g';JavaScript中的选项

如何使用带有';g';JavaScript中的选项,javascript,regex,Javascript,Regex,假设我有这样一个url: url = http://www.example.com/listing.html?pid=1234&pid=1235&pid=1236 ["1234", "1235", "1236"] 如何使用regex仅提取'pid='之后的值,而不使用regex提取文本本身 下面是我的正则表达式现在的样子: url.match(/pid=(\w+)/g) 它给出了以下输出: ["pid=1234", "pid=1235", "pid=1236"] 但我想这

假设我有这样一个url:

url = http://www.example.com/listing.html?pid=1234&pid=1235&pid=1236
["1234", "1235", "1236"]
如何使用regex仅提取'pid='之后的值,而不使用regex提取文本本身

下面是我的正则表达式现在的样子:

url.match(/pid=(\w+)/g)
它给出了以下输出:

["pid=1234", "pid=1235", "pid=1236"]
但我想这样做:

url = http://www.example.com/listing.html?pid=1234&pid=1235&pid=1236
["1234", "1235", "1236"]

如果我在这里做错了什么,请纠正我。

正则表达式可以包含一个称为正向查找断言的内容,如下所述:

我目前无法测试JavaScript的regexp是否会做到这一点,但如果是这样的话,就完成了。如果没有,可以使用“=”作为分隔符对现有regexp的结果执行JS split(),以获得所需的结果。也许没有单个regexp那么整洁,但它将完成任务

编辑后补充:我很确定zessx甚至在发表评论之前都是正确的。这项工作:

var pids = [];
var url = "http://www.example.com/listing.html?pid=1234&pid=1235&pid=1236";
var result = url.match(/pid=(\w+)/g);
for (var i=0; i<result.length; i++) {
    pids[i] = result[i].split("=")[1];
    console.log(pids[i]);
}
var-pids=[];
变量url=”http://www.example.com/listing.html?pid=1234&pid=1235&pid=1236";
var result=url.match(/pid=(\w+)/g);

对于(var i=0;i而言,简单的解决方案是:

url.match(/(?<=pid=)(\d+)/g);

您可以使用简单的函数方法,如下所示

var url = "http://www.example.com/listing.html?pid=1234&pid=1235&pid=1236";

console.log(url.split("&").map(function(currentString) {
    return currentString.split("=")[1];
}));
# [ '1234', '1235', '1236' ]
  • 首先,按
    &

  • 然后按
    =
    拆分每个拆分部分,并收集所有第二个元素


  • 您也可以这样做,而无需拆分/替换结果数据:

    url = 'http://www.example.com/listing.html?pid=1234&pid=1235&pid=1236';    
    regex = /(?:pid=)(\w+)/g    
    var data =[];
    
    while ((result = regex.exec(url)) !== null) {
      data.push(result[1]);      
    }
    console.log(data);
    
    // Result Array [ "1234", "1235", "1236" ]
    

    Javascript现在支持向前看,但不支持向后看。有一个示例说明如何枚举字符串中的正则表达式匹配项。返回的
    RegExp.exec
    对象将给出正则表达式的分组匹配项。如果所有查询字符串参数都是pid=,则可以这样做,但如果不是,我认为可能会失败。