繁体   English   中英

匹配正则表达式-JavaScript

[英]match regular expression - JavaScript

所以我有以下网址:

var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";

我想从中取出用户名和令牌;

我试过了:

var match = (/#\{(.*?)\}/g.exec(oURL));
console.log(match);

但这给了我:

["#{username}", "username", index: 27, input: "https://graph.facebook.com/#{username}/posts?access_token=#{token}"

为什么不捕获令牌?

谢谢

问题是,无论何时调用, exec仅从给定索引返回第一个匹配项。

退货

如果匹配成功,则exec()方法返回一个数组并更新正则表达式对象的属性。 返回的数组具有匹配的文本作为第一项,然后是每个与捕获的括号匹配的项,其中包含捕获的文本。

如果匹配失败,则exec()方法返回null。

您将需要循环,再次连续匹配以找到所有匹配项。

 var matches = [], match, regex = /#\\{(.*?)\\}/g, oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}"; while (match = regex.exec(oURL)) { matches.push(match) } console.log(matches) 

但是,如果仅对第一个捕获组感兴趣,则只能将它们添加到matchs数组中:

 var matches = [], match, regex = /#\\{(.*?)\\}/g, oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}"; while (match = regex.exec(oURL)) { matches.push(match[1]) } console.log(matches) 

尝试以下方法:

oURL.match(/#\\{(.*?)\\}/g)

您接受的答案是完美的,但我想我还要补充一点,创建这样的小助手功能非常容易:

function getMatches(str, expr) {
  var matches = [];
  var match;
  while (match = expr.exec(str)) {
    matches.push(match[1]);
  }
  return matches;
}

然后,您可以更直观地使用它。

var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
var expr = /#\{([^\{]*)?\}/g;
var result = getMatches(oURL, expr);
console.log(result);

http://codepen.io/Chevex/pen/VLyaeG

尝试这个:

var match = (/#\{(.*?)\}.*?#\{(.*?)\}/g.exec(oURL));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM