Regex - find all links on twitter

My regular expression is bad and allows me to go down, so some help would be wonderful here.

All I want to do is return all the links that appear on the tweet (line only). Some examples:

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

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

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

It should also support multiple links: "read http://mytest.com/blog/post.html and http://mytest.com/blog/post_two.html"

Any help would be great!

thanks

Ben

+3
source share
4 answers

Try the following:

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

Update:

To catch links starting with "www." (there is no http: // "prefix), you can try the following:

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

+2
source

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

Found this one here

^(?#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|[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})*)?$ 
+1
source

I understand this question is from 2009, but now the Twitter API now returns URLs (and extends t.co links).

0
source

Source: https://habr.com/ru/post/1717541/


All Articles