Regex string issue in making plain text urls clickable

前端 未结 4 856
死守一世寂寞
死守一世寂寞 2021-01-05 15:48

I need a working Regex code in C# that detects plain text urls (http/https/ftp/ftps) in a string and make them clickable by putting an anchor tag around it with same url. I

4条回答
  •  孤街浪徒
    2021-01-05 16:12

    I noticed in your example test string that if a duplicate link e.g. ftp://www.abc.com is in the string and is already linked then the result will be to double anchor that link. The Regular Expression that you already have and that @stema has supplied will work, but you need to approach how you replace the matches in the sContent variable differently.

    The following code example should give you what you want:

    string sContent = "ttt ftp://www.abc.com abc ftp://www.abc.com abbbbb http://www.abc2.com";
    
    Regex regx = new Regex("(?]*>))(http|https|ftp|ftps)://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
    
    MatchCollection matches = regx.Matches(sContent);
    
    for (int i = matches.Count - 1; i >= 0 ; i--)
    {
        string newURL = "" + matches[i].Value + "";
    
       sContent = sContent.Remove(matches[i].Index, matches[i].Length).Insert(matches[i].Index, newURL);
    }
    

提交回复
热议问题