简体   繁体   English

匹配正则表达式-JavaScript

[英]match regular expression - JavaScript

So I have the following url: 所以我有以下网址:

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

I want to take username and token out of it; 我想从中取出用户名和令牌;

I tried: 我试过了:

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

but it is giving me: 但这给了我:

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

Why isn't catching token? 为什么不捕获令牌?

Thanks 谢谢

The problem is that exec only returns the first match from the given index whenever called. 问题是,无论何时调用, exec仅从给定索引返回第一个匹配项。

Returns 退货

If the match succeeds, the exec() method returns an array and updates properties of the regular expression object. 如果匹配成功,则exec()方法返回一个数组并更新正则表达式对象的属性。 The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured. 返回的数组具有匹配的文本作为第一项,然后是每个与捕获的括号匹配的项,其中包含捕获的文本。

If the match fails, the exec() method returns null. 如果匹配失败,则exec()方法返回null。

You would need to loop, continuously matching again to find all the matches. 您将需要循环,再次连续匹配以找到所有匹配项。

 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) 

However, if you are only interested in the first capture group, you can only add those to the matches array: 但是,如果仅对第一个捕获组感兴趣,则只能将它们添加到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)

The answer you accepted is perfect, but I thought I'd also add that it's pretty easy to create a little helper function like this: 您接受的答案是完美的,但我想我还要补充一点,创建这样的小助手功能非常容易:

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

Then you can use it a little more intuitively. 然后,您可以更直观地使用它。

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 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