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;
1

2 Answers 2

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>";
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.