正则表达式 – 在推文中查找所有链接

我的正则表现很差,让我失望所以这里的一些帮助会很棒。

我想做的就是返回推文中出现的所有链接(只是一个字符串) – 一些例子是:

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

任何帮助都会很棒!

谢谢

试试这个:

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

更新:

捕获以“www。”开头的链接。 也是(没有“http://”前缀),你可以试试这个:

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

这是我编写的一个解析推文源的网站的代码片段。 它解析链接,哈希标记和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, "https://stackoverflow.com/questions/1416544/regex-find-all-links-in-a-tweet/" + m.Value + ""); } re = new Regex(@"(@)(\w+)"); mc = re.Matches(tweetStream[i].Text); foreach (Match m in mc) { str = str.Replace(m.Value, "https://stackoverflow.com/questions/1416544/regex-find-all-links-in-a-tweet/" + m.Value + ""); } re = new Regex(@"(#)(\w+)"); mc = re.Matches(tweetStream[i].Text); foreach (Match m in mc) { str = str.Replace(m.Value, "https://stackoverflow.com/questions/1416544/regex-find-all-links-in-a-tweet/" + m.Value + ""); } tweets += string1 + "
" + str + "
" + string2; }

在这里找到了这个

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

我意识到这个问题是从2009年开始的,但Twitter的API现在返回URL(并扩展了t.co链接)。