1

I want a regex expression that will match;

  1. www
  2. http
  3. https

It should make only urls in the string clickable. What is the best way to do this?

What I have now is this, but this doesn't match www. Also, I don't know how to make the entire text visible in the label, not just the links. I guess this could be done with some space separation and recursive loops, if someone has a good idea I'd be happy to hear it.

Regex r = new Regex(@"(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?");


            // Match the regular expression pattern against a text string.
            if (valueString != null)
            {
                Match m = r.Match(valueString);
                if (m.Success)
                {
                    labelHtml = "<a href=\"" + m.Value + "\">" + m.Value + "</a>";
                }
            }
            ((Label)control).Text = labelHtml;
Soroush Hakami
  • 5,226
  • 15
  • 66
  • 99

2 Answers2

3

Anton Hansson gave you link to valid regex and replacement code. Below is more advaced way if you wan't to do something more with found urls etc.

var regex = new Regex("some valid regex");
var text = "your original text to linkify";
MatchEvaluator evaluator = LinkifyUrls;
text = regex.Replace(text, evaluator);

...

private static string LinkifyUrls(Match m)
{
    return "<a href=\"" + m.Value + "\">" + m.Value + "</a>";
}
Episodex
  • 4,479
  • 3
  • 41
  • 58
0

You could use Uri class. It does the validation.

var url = new Uri("http://www.google.com");
var text = url.ToString();

It throws the exception if it is invalid url. You can use static Uri.TryCreate if having exceptions is not an option.

Alex Aza
  • 76,499
  • 26
  • 155
  • 134