Find url in plain text and insert HTML A markups

后端 未结 1 1581
鱼传尺愫
鱼传尺愫 2021-01-07 04:51

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          


        
相关标签:
1条回答
  • 2021-01-07 05:51

    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));
    }
    
    0 讨论(0)
提交回复
热议问题