使用Html Agility Pack从文本内部URL创建Html链接

时间:2013-03-20 14:51:51

标签: c# html-agility-pack

如何使用Html Agility Pack + c#将文件从文本转换为HTML链接?

例如:“www.stackoverflow.com是一个非常酷的网站。”

输出:

"<a href="www.stackoverflow.com">www.stackoverflow.com</a>  is a very cool site."

2 个答案:

答案 0 :(得分:3)

感谢@ user1778606的回答。虽然它仍然使用了一些正则表达式,但我得到了它的工作。它工作得更好更安全(即它永远不会在超链接和href属性中创建超链接)。

        //convert text to html
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(inputString);

        // \w* - means it can start with any alphanumeric charactar
        // \s+ - was placed to replace all white spaces (when there is more than one word).
        // \b - set bounderies for the keyword
        const string pattern = @"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[.\!\/\\w]*))?)";

        //get all elements text propery except for anchor element 
        var nodes = doc.DocumentNode.SelectNodes("//text()[not(ancestor::a)]") ?? new HtmlAgilityPack.HtmlNodeCollection(null);

        foreach (var node in nodes)
        {
            Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
            node.InnerHtml = regex.Replace(node.InnerHtml, "<a href=\"$1\">$1</a>").Replace("href=\"www", "href=\"http://www");
        }

        return doc.DocumentNode.OuterHtml;

答案 1 :(得分:0)

我很确定它有可能,虽然我没有尝试过。

以下是如何使用链接替换文档中的固定字符串

  

Find keyword in text when keyword match certain conditions - C#

继承人如何为网址设置正则表达式

  

regular expression for url

将它们放在一起,应该是可能的。

伪代码

  

选择所有文本节点

     
    每个节点

         
      

获取内部文本
      在文中找到网址(使用正则表达式?)
      找到每个网址

             
        

用字符串文字链接标记(a href = etc ...)

替换url的文本