2012-09-10 21 views
2

我正在製作一個書籤,以便在Google Plus上使用。我對我的正則表達式有點輕,但下面的測試差不多的作品。正則表達式來拾取部分URL返回數組與「undefined」

/\/([0-9]{10,30})|(\+[^\/]{2,30})\//.exec(window.location.pathname); 

的或之前的第一部分工作正常提取舊式用戶ID號碼,但第二部分,在相同的位置與「未定義」數組提取新的虛榮心式ID的回報。

舊式的URL是這樣的:

https://plus.google.com/u/0/113917445082638587047/posts 
https://plus.google.com/113917445082638587047/posts 

一個典型的個性化網址如下:

https://plus.google.com/u/0/+MarkTraphagen/posts 
https://plus.google.com/+MarkTraphagen/posts 

對於個性化網址,我的正則表達式返回此:

["+MarkTraphagen/", undefined, "+MarkTraphagen"] 

「undefined」從何而來?我如何擺脫它?


注:上面的字符串長度(10至30和2〜30)是在花露水的可接受的pH水平大致基礎的,所以考慮到在使用它們之前。

+0

僅供參考,關於谷歌加,這裏是從文檔標題拉適當的名稱正則表達式,佔括號中的可選通知計數:/ ^( \([0-9] {0,3} \)\ S)([\ S \ S] +)\ S- \ sGoogle/.exec(document.title時)?; – Billbad

+0

我不知道你是否使用任何Api客戶端,因爲我有麻煩讓PHP API客戶端與虛榮的URL,尤其是因爲他們重定向到/後,/約,/視頻等。 – developer10

回答

4

將您捕捉搶到第一或第二形態:

/\/([0-9]{10,30}|\+[^\/]{2,30})\//.exec(window.location.pathname); 

,那麼你只需要一個捕獲的值,無論是形式#1或形式#2。

未定義來了,因爲你有2個捕獲,第一個不存在。

+0

這很好! – Billbad

1

以下是可能爲您的問題的解決方案的正則表達式模式。廁所水的pH值不應該影響正則表達式,這是一個常見的規則。

/\/(\d{4,}|\+\w+?)\//g.exec(window.location.pathname); 

你可以看到的結果here

請注意,您可以用任何你喜歡的東西來替換正則表達式中的4。該數字是捕獲所需的最小位數。我不確定Google ID的格式是什麼,因此您可能需要將該號碼更改爲10,例如,如果您確定ID從未少於10位數字。

模式的解釋是在這裏:

// /(\d{4,}|\+\w+?)/ 
// 
// Match the character 「/」 literally «/» 
// Match the regular expression below and capture its match into backreference number 1 «(\d{4,}|\+\w+?)» 
// Match either the regular expression below (attempting the next alternative only if this one fails) «\d{4,}» 
//  Match a single digit 0..9 «\d{4,}» 
//   Between 4 and unlimited times, as many times as possible, giving back as needed (greedy) «{4,}» 
// Or match regular expression number 2 below (the entire group fails if this one fails to match) «\+\w+?» 
//  Match the character 「+」 literally «\+» 
//  Match a single character that is a 「word character」 (letters, digits, and underscores) «\w+?» 
//   Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?» 
// Match the character 「/」 literally «/» 
+1

這是一些很好解釋,教育的東西。非常感謝。 – Billbad