Converting URLs in Text to Hyperlinks

by Digvijay 13. June 2008 14:43

Here is a small code snippet to accomplish it:

 

        string str = TextBox1.Text;// some text like "go to http://blog.digvijay.eu"
        string patten = @"(http://|https://|[])+([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
        Regex chr = new Regex(patten, RegexOptions.IgnoreCase);
        Match m;
        for (m = chr.Match(str); m.Success; m = m.NextMatch())
        {
            string result = m.Groups[0].ToString();
            
            // If no protocol specified it will be with "http://" as default.
            if (result.IndexOf("://") == -1)
                result = "http://" + result; 

            // you may specify nofollow and open in new window and like here
            str = str.Replace(m.Groups[0].ToString(),
            "<a href='" + result + "'  target='_blank' >" + m.Groups[0].ToString() + "</a>");

        }
        return str;

Tags:

Code Snippets | RegEx

Scanning a Text Document or Web Page for Email IDs

by Digvijay 9. June 2008 22:45

We can use a simple function as below to find all email IDs embedded in a text or html file. I just thought i could share it with everyone:

   1:          private string[] GetEmailsFromMessage(string messageBody)
   2:          {
   3:   
   4:              if (string.IsNullOrEmpty(messageBody) || messageBody.Trim().Length == 0)
   5:                  return string.Empty;
   6:   
   7:              List<string> oEmails = new List<string>();
   8:              Regex regex = new Regex(@"[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]",RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);
   9:   
  10:              MatchCollection expressionmatch = regex.Matches(messageBody);
  11:   
  12:              if (expressionmatch.Count > 0)
  13:              {
  14:                  foreach (Match m in expressionmatch)
  15:                      oEmails.Add(m.Value);
  16:              }
  17:              if (oEmails.Count > 0)
  18:                  return oEmails.ToArray();
  19:              else
  20:                  return null;
  21:   
  22:          }

Technorati Tags:

Tags:

Code Snippets | RegEx

 

About Digvijay

  Digvijay Chauhan
I am a developer living in Stockholm, Sweden and I love to program and work on cutting edge technologies in the Microsoft Technology space.

LinkedIn Twitter StackOverflow

Certifications

Digvijay Chauhan Microsoft Certification Logo

Other Pages

RecentPosts

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

Most comments

Live Traffic

Live Traffic Feed
  Västra Frölunda, Vastra Gotaland arrived from digvijay.eu on "blank_page"

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Translate