2

I have text with URL and I need to wrap them with HTML A markup, how to do that in c#?

Example, I have

My text and url http://www.google.com The end.

I would like to get

My text and url <a href="http://www.google.com">http://www.google.com</a> The end.
H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
Tomas
  • 17,551
  • 43
  • 152
  • 257

1 Answers1

14

You can use a regex for this. If you need a better Regex you can search for it here http://regexlib.com/Search.aspx?k=url

My quick solution for this would be this:

string mystring = "My text and url http://www.google.com The end.";

Regex urlRx = new Regex(@"(?<url>(http:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)", RegexOptions.IgnoreCase);

MatchCollection matches = urlRx.Matches(mystring);

foreach (Match match in matches)
{
    var url = match.Groups["url"].Value;
    mystring = mystring.Replace(url, string.Format("<a href=\"{0}\">{0}</a>", url));
}
sohtimsso1970
  • 3,216
  • 4
  • 28
  • 38
nhu
  • 470
  • 1
  • 5
  • 10
  • 1
    Just used this, use "Regex urlRx = new Regex(@"(?(http[s]?:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)", RegexOptions.IgnoreCase);" (note the [s]?) for https-url's. – Mee Dec 24 '20 at 10:51