Linkify URLs in string with Regex expression
I want a regex expression that will match;
- www
- http
- 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|h开发者_Go百科ttps):\/\/(\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;
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>";
}
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.
精彩评论