2009-09-13 100 views
3

我的正則表達式很差,讓我失望,所以在這裏有一些幫助。正則表達式 - 查找推文中的所有鏈接

所有我想要做的是返回所有出現在推特(只是一個字符串)的鏈接 - 一些例子是:

"Great summary http://mytest.com/blog/post.html (#test)

"http://mytest.com/blog/post.html (#test)

"post: http://mytest.com/blog/post.html"

它應該還支持多個鏈接,如: "read http://mytest.com/blog/post.html and http://mytest.com/blog/post_two.html"

任何幫助都會很棒!

感謝

+0

這取決於你想得到多麼具體。也許發佈你使用的正則表達式,以及你沒有捕捉到的情況可能是有用的。 – 2009-09-13 00:55:27

回答

2

試試這個:

/\bhttps?:\/\/\S+\b/

更新:

爲了趕上開頭鏈接 「WWW」。太(沒有「HTTP://」前綴),你可以試試這個:

/\b(?:https?:\/\/|www\.)\S+\b/

+0

我認爲你可以在沒有http(s)的推文中發佈鏈接。所以這會失敗,像「我真的很喜歡www.this-site.com」。 – 2009-09-13 01:02:38

+0

嗯。有趣。好評。我更新了我的答案,以檢測以「www」開頭的鏈接。太。 – Asaph 2009-09-13 01:12:11

+1

好吧,現在怎麼樣「哇,stackoverflow.com太棒了!」? :P – 2009-09-13 01:31:14

1

下面是從一個網站,我寫了解析Twitter源代碼片斷。它解析鏈接,哈希標記和twitter用戶名。到目前爲止,它工作得很好。我知道這不是Ruby,但正則表達式應該是有幫助的。

if(tweetStream[i] != null) 
        { 
         var str = tweetStream[i].Text; 
         var re = new Regex(@"http(s)?:\/\/\S+"); 
         MatchCollection mc = re.Matches(tweetStream[i].Text); 

         foreach (Match m in mc) 
         { 
          str = str.Replace(m.Value, "<a href='" + m.Value + "' target='_blank'>" + m.Value + "</a>"); 
         } 
         re = new Regex(@"(@)(\w+)"); 
         mc = re.Matches(tweetStream[i].Text); 
         foreach (Match m in mc) 
         { 
          str = str.Replace(m.Value, "<a href='http://twitter.com/" + m.Value.Replace("@",string.Empty) + "' target='_blank'>" + m.Value + "</a>"); 
         } 
         re = new Regex(@"(#)(\w+)"); 
         mc = re.Matches(tweetStream[i].Text); 
         foreach (Match m in mc) 
         { 
          str = str.Replace(m.Value, "<a href='http://twitter.com/#search?q=" + m.Value.Replace("#", "%23") + "' target='_blank'>" + m.Value + "</a>"); 
         } 
         tweets += string1 + "<div>" + str + "</div>" + string2; 
        } 
1

發現這是here

^(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~/|/)?(?#Username:Password)(?:\w+:\[email protected])?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$ 
+0

+1之前檢查非空格字符,以便讓我微笑。 :d – 2009-09-13 02:27:37

0

我意識到這個問題是從2009年,但Twitter的API現在返回網址(擴大t.co鏈接)。

相關問題