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