如何将多个实例与 JavaScript 中的正则表达式进行匹配,类似于 PHP 的 preg_match_all()?

2022-08-30 02:24:39

我正在尝试解析由键=值对组成的url编码字符串,这些字符串由或分隔。&&

以下内容将仅匹配第一个匹配项,将键和值分解为单独的结果元素:

var result = mystring.match(/(?:&|&)?([^=]+)=([^&]+)/)

字符串“1111342=Adam%20Franco&348572=Bob%20Jones”的结果为:

['1111342', 'Adam%20Franco']

使用全局标志“g”将匹配所有匹配项,但仅返回完全匹配的子字符串,而不返回分隔的键和值:

var result = mystring.match(/(?:&|&)?([^=]+)=([^&]+)/g)

字符串“1111342=Adam%20Franco&348572=Bob%20Jones”的结果为:

['1111342=Adam%20Franco', '&348572=Bob%20Jones']

虽然我可以单独拆分字符串并分离每个键/值对,但有没有办法使用JavaScript的正则表达式支持来匹配类似于PHP函数的模式的多次出现?&/(?:&|&)?([^=]+)=([^&]+)/preg_match_all()

我的目标是通过某种方式获得结果,并将子匹配分开,例如:

[['1111342', '348572'], ['Adam%20Franco', 'Bob%20Jones']]

[['1111342', 'Adam%20Franco'], ['348572', 'Bob%20Jones']]

答案 1

从评论中吊起

2020年评论:我们现在拥有URLSearchParams,它为我们完成了所有这些工作,因此不再需要自定义代码,更不用说正则表达式了。

Mike 'Pomax' Kamermans

此处列出了浏览器支持 https://caniuse.com/#feat=urlsearchparams


我建议使用另一个正则表达式,使用子组单独捕获参数的名称和值,并 re.exec()

function getUrlParams(url) {
  var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
      match, params = {},
      decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};

  if (typeof url == "undefined") url = document.location.href;

  while (match = re.exec(url)) {
    params[decode(match[1])] = decode(match[2]);
  }
  return params;
}

var result = getUrlParams("http://maps.google.de/maps?f=q&source=s_q&hl=de&geocode=&q=Frankfurt+am+Main&sll=50.106047,8.679886&sspn=0.370369,0.833588&ie=UTF8&ll=50.116616,8.680573&spn=0.35972,0.833588&z=11&iwloc=addr");

result是一个对象:

{
  f: "q"
  geocode: ""
  hl: "de"
  ie: "UTF8"
  iwloc: "addr"
  ll: "50.116616,8.680573"
  q: "Frankfurt am Main"
  sll: "50.106047,8.679886"
  source: "s_q"
  spn: "0.35972,0.833588"
  sspn: "0.370369,0.833588"
  z: "11"
}

正则表达式分解如下:

(?:            # non-capturing group
  \?|&         #   "?" or "&"
  (?:amp;)?    #   (allow "&", for wrongly HTML-encoded URLs)
)              # end non-capturing group
(              # group 1
  [^=]+      #   any character except "=", "&" or "#"; at least once
)              # end group 1 - this will be the parameter's name
(?:            # non-capturing group
  =?           #   an "=", optional
  (            #   group 2
    [^]*     #     any character except "&" or "#"; any number of times
  )            #   end group 2 - this will be the parameter's value
)              # end non-capturing group

答案 2

您需要使用“g”开关进行全局搜索

var result = mystring.match(/(&|&)?([^=]+)=([^&]+)/g)