Regex string issue in making plain text urls clickable

前端 未结 4 877
死守一世寂寞
死守一世寂寞 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:10

    Check out: Detect email in text using regex and Regex URL Replace, ignore Images and existing Links, just replace the regex for links, it will never replace a link inside a tag, only in contents.

    http://html-agility-pack.net/?z=codeplex

    Something like:


    string textToBeLinkified = "... your text here ...";
    const string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
    Regex urlExpression = new Regex(regex, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
    
    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(textToBeLinkified);
    
    var nodes = doc.DocumentNode.SelectNodes("//text()[not(ancestor::a)]") ?? new HtmlNodeCollection();
    foreach (var node in nodes)
    {
        node.InnerHtml = urlExpression.Replace(node.InnerHtml, @"$0");
    }
    string linkifiedText = doc.DocumentNode.OuterHtml;
    

提交回复
热议问题