使用Regex将空span标记替换为br标记

时间:2011-01-31 11:53:31

标签: c# regex c#-4.0

任何人都可以告诉我正则表达式模式,它检查空的span标签并用标签替换它们。

如下所示:

string io = Regex.Replace(res,"" , RegexOptions.IgnoreCase);

我不知道要传递的模式!

4 个答案:

答案 0 :(得分:2)

此模式将找到所有空的span标记,例如<span/><span></span>

<span\s*/>|<span>\s*</span>

因此,此代码应使用br标记替换所有空span标记:

string io = Regex.Replace(res, @"<span\s*/>|<span>\s*</span>", "<br/>");

答案 1 :(得分:2)

Jeff Mercado的代码在行上有错误:

.Where(e => e.Name.Equals("span", StringComparison.OrdinalIgnoreCase) && n.Name.Equals("span", StringComparison.OrdinalIgnoreCase)

错误讯息:Member 'object.Equals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead

当我尝试替换其他物体时,它们无效!

答案 2 :(得分:0)

我对这个问题最喜欢的答案是:RegEx match open tags except XHTML self-contained tags

答案 3 :(得分:0)

你应该解析它,搜索空的span元素并替换它们。以下是使用LINQ to XML进行操作的方法。请注意,根据实际的HTML,可能需要调整才能使其工作,因为 是XML解析器,而不是HTML。

// parse it
var doc = XElement.Parse(theHtml);

// find the target elements
var targets = doc.DescendantNodes()
                 .OfType<XElement>()
                 .Where(e => e.Name.Equals("span", StringComparison.OrdinalIgnoreCase)
                          && e.IsEmpty
                          && !e.HasAttributes)
                 .ToList(); // need a copy since the contents will change

// replace them all
foreach (var span in targets)
    span.ReplaceWith(new XElement("br"));

// get back the html string
theHtml = doc.ToString();

否则,这里有一些代码显示如何使用HTML Agility Pack执行相同的操作(以与其他版本相同的方式编写)。

// parse it
var doc = new HtmlDocument();
doc.LoadHtml(theHtml);

// find the target elements
var targets = doc.DocumentNode
                 .DescendantNodes()
                 .Where(n => n.NodeType == HtmlNodeType.Element
                          && n.Name.Equals("span", StringComparison.OrdinalIgnoreCase)
                          && !n.HasChildNodes && !n.HasAttributes)
                 .ToList(); // need a copy since the contents will change

// replace them all
foreach (var span in targets)
{
    var br = HtmlNode.CreateNode("<br />");
    span.ParentNode.ReplaceChild(br, span);
}

// get back the html string
using (StringWriter writer = new StringWriter())
{
    doc.Save(writer);
    theHtml = writer.ToString();
}
相关问题