Twitterify your strings using c# regex


So you’ve set up a twitter feed on your site – sweet. Now all your peeps can see how excited you are about the new limited edition Whitney Houston EP you’ve been listening to. But then you post a link – or a reply to a fellow twitterati member and those handy auto links you’ve become so used to aren’t there. Bummer duuude – lets fix that.

twitter-bird-logo Live and die by the Regex

As usually is the way with these things, Regex is the dark knight swoops in the night to save the day (no, not batman) – this case is no different. A few simple regex matches and we’re done.

What we want to replace:

  • All links starting with http://
  • All links starting with www
  • All twitter username links ie. @dougrathbone
  • All twitter hash tag links ie. #chucknorris


Let take a look at the code

The method i have listed below takes a twitter status string and applies all these rules:

public static String AddWebAndTwitterLinks(string input)
    string strWebLinks = @"(^|[\n ])([\w]+?://[\w]+[^ \n\r\t< ]*)";
    string strWebLinksWWW = @"(^|[\n ])((www|ftp)\.[^ \t\n\r< ]*)";
    string strTwitterNames = @"@(\w+)";
    string strTwitterTags = @"#(\w+)";
    input = Regex.Replace(input, strWebLinks, 
        " <a href=\"$2\" target=\"_blank\">$2</a>");
    input = Regex.Replace(input, strWebLinksWWW, 
        " <a href=\"http://$2\" target=\"_blank\">$2</a>");
    input = Regex.Replace(input, strTwitterNames, 
        "<a href=\"$1\" target=\"_blank\">@$1</a>");
    input = Regex.Replace(input, strTwitterTags, 
        "<a href=\"$1\" target=\"_blank\">#$1</a>");

    return input;

And there we have it! An example of this in use if the twitter feed on the right hand side of this very page!