c#删除特定的<a> tags (e-mail only) in a string

时间:2016-12-15 16:47:37

标签: c# .net model-view-controller

So I get a string like this from an external method:

var myString = "<p>Lorem &sect; 5 ipsum</p>\r\n<p><p>E-Mail: <a href=\"email@domain.com\">email@domain.com</a></p>\r\n<p>Lorem ipsum dolor sit amet</p><p><a href=\"http://www.adress.com\">name</a></p>\r\n";

I want to replace all e-mail addresses (no other links) with plain text. So afterwards my link should look something like this:

var myClearedString = "<p>Lorem &sect; 5 ipsum</p>\r\n<p><p>E-Mail: email@domain.com</p>\r\n<p>Lorem ipsum dolor sit amet</p><p><a href=\"http://www.adress.com\">name</a></p>\r\n"

There could be 1 to n occurrences in the string. I already searched stackoverflow, but the only thing related was this question: Replace mailto-links

在我看来,这是将字符串转换为XML并搜索它的最佳方法。不幸的是,我的字符串中的一些字符似乎引起了麻烦(我假设它可能是\ n或\ r)。

4 个答案:

答案 0 :(得分:3)

您应该查看Html AgilityPack。我确信有很多正则表达式可以帮到你,但使用Regex解析HTML通常是一个坏主意。有以下原因,请参阅https://stackoverflow.com/a/1732454/880642

Agility pack将为您安全地解析文档,并让您遍历它以查找符合您条件的链接。

var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(htmlPage);
var links = htmlDocument.DocumentNode.SelectNodes("//a[@href]");
foreach (var node in links)
{
    HtmlAttribute attribute = node.Attributes["href"];
    if(IsEmail(attribute.Value))
         node.ParentNode.RemoveChild(node, true); //<-- keepGrandChildren
}
var newhtml = htmlDocument.DocumentNode.OuterHtml;

您可以使用正则表达式来验证属性值是电子邮件还是任意数量的.Net函数,以查看字符串是否为电子邮件。我很惊讶这些不是mailto:链接,但您必须使用您拥有的数据。

答案 1 :(得分:1)

我可能会因为建议这样做而挂起,但你可以使用正则表达式。

首先包括必要的依赖:

using System.Text.RegularExpressions;

然后我们需要找出能够识别符合条件的子字符串的正则表达式。有几个站点提供正则表达式测试。只需搜索“正则表达式测试程序”。

这将获得每个锚标记,并创建3个组:

(<a[^>]+>)(.*?)(<\/a>)

现在我们需要获取所有匹配项并将其替换为纯文本值。

我们可以使用Regex.Replace方法来完成任务:

string newValue = Regex.Replace(test, @"(<a[^>]+>)(.*?)(<\/a>)", (m) => 
{
    return m.Groups[2].Value;
});

此代码段正在为匹配的每个实例运行lambda表达式。然后返回第二组中的值(作为标记的内容)。

答案 2 :(得分:0)

这将是一个很好的使用正则表达式和替换

Regex.Replace(myString, @"(<a.*?>)", "").Replace("</a>","")

答案 3 :(得分:-1)

您可以使用:

Regex.Replace(source, "<a.*?>", string.Empty);

或者如果您想要更换次数,可以使用已编译的正则表达式:

Regex removeRegex = new Regex("<a.*?>", RegexOptions.Compiled);

并使用如下:

removeRegex.Replace(source, string.Empty);