2009-09-13 52 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链接)。

相关问题