我需要将内联css样式属性转换为HTML标记equivelants.我已经工作的解决方案,但使用Microsoft .Net Regex命名空间和长文档(约40页的html)非常缓慢地运行.我尝试了几种变化,但没有有用的结果.我已经完成了执行表达式的一些包装,但最后它只是被调用的内置正则表达式Replace方法.
我确定我正在滥用正则表达式的贪婪,但我不确定如何使用单个正则表达式实现我想要的东西.
我希望能够运行以下单元测试:
[Test]
public void TestCleanReplacesFontWeightWithB()
{
string html = "<font style=\"font-weight:bold\">Bold Text</font>";
html = Q4.PrWorkflow.Helper.CleanFormatting(html);
Assert.AreEqual("<b>Bold Text</b>", html);
}
[Test]
public void TestCleanReplacesMultipleAttributesFontWeightWithB()
{
string html = "<font style=\"font-weight:bold; color: blue; \">Bold Text</font>";
html = Q4.PrWorkflow.Helper.CleanFormatting(html);
Assert.AreEqual("<b>Bold Text</b>", html);
}
[Test]
public void TestCleanReplaceAttributesBoldAndUnderlineWithHtml()
{
string html = "<span style=\"font-weight:bold; color: blue; text-decoration: underline; \">Bold Text</span>";
html = Q4.PrWorkflow.Helper.CleanFormatting(html);
Assert.AreEqual("<u><b>Bold Text</b></u>", html);
}
[Test]
public void TestCleanReplaceAttributesBoldUnderlineAndItalicWithHtml()
{
string html = "<span style=\"font-weight:bold; color: blue; font-style: italic; text-decoration: underline; \">Bold Text</span>";
html = Q4.PrWorkflow.Helper.CleanFormatting(html);
Assert.AreEqual("<u><b><i>Bold Text</i></b></u>", html);
}
[Test]
public void TestCleanReplacesFontWeightWithSpaceWithB()
{
string html = "<font size=\"10\" style=\"font-weight: bold\">Bold Text</font>";
html = Q4.PrWorkflow.Helper.CleanFormatting(html);
Assert.AreEqual("<b>Bold Text</b>", html);
}
Run Code Online (Sandbox Code Playgroud)
我用来实现这个逻辑的常规表达工作但非常慢.c#代码中的正则表达式如下所示:
public static IReplacePattern IncludeInlineItalicToITag(ICleanUpHtmlFactory factory)
{
return factory.CreateReplacePattern("(<(span|font) .*?style=\".*?font-style:\\s*italic[^>]*>)(.*?)</\\2>", "$1<i>$3</i></$2>");
}
public static IReplacePattern IncludeInlineBoldToBTag(ICleanUpHtmlFactory factory)
{
return factory.CreateReplacePattern("(<(span|font) .*?style=\".*?font-weight:\\s*bold[^>]*>)(.*?)</\\2>", "$1<b>$3</b></$2>");
}
public static IReplacePattern IncludeInlineUnderlineToUTag(ICleanUpHtmlFactory factory)
{
return factory.CreateReplacePattern("(<(span|font) .*?style=\".*?text-decoration:\\s*underline[^>]*>)(.*?)</\\2>", "$1<u>$3</u></$2>");
}
Run Code Online (Sandbox Code Playgroud)
我认为问题在于,如果找到没有定义样式属性的span | font标签,由于".*?",它将继续查找它直到文档结尾.我没有测试过它,但把它改成"[^>]*?" 可能会提高性能.
编辑:确保您对所有".*?"应用该更改.你有; 甚至是捕获标签之间内容的那个(使用"[^ <]*?"),因为如果文件格式不正确,它将捕获到下一个结束标记.