Мне нужно преобразовать встроенные атрибуты стиля CSS в их эквивалентные теги HTML. Решение, которое у меня есть, работает, но работает ОЧЕНЬ медленно, используя пространство имен Microsoft .Net Regex и длинные документы (~ 40 страниц HTML). Я пробовал несколько вариантов, но без каких-либо полезных результатов. Я немного поработал над выполнением выражений, но в итоге вызывается только встроенный метод Regex 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);
}
Обычное выражение, которое я использую для достижения этой логики, работает, но ОЧЕНЬ медленно. Регулярное выражение в коде 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>");
}