使用正则表达式删除块标记后的换行符

时间:2014-12-16 15:24:13

标签: c# regex replace

我想删除阻止标记之后的换行符,例如h1, h2, ul, blockquote等,然后再将它们转换为PDF。

我目前正在使用string.Replace方法,如下所示。 RegEx是否有更好的解决方案?

text = text.Replace("center]\r\n", "center]")
            .Replace("li]\r\n", "li]")
            .Replace("ol]\r\n", "ol]")
            .Replace("ul]\r\n", "ul]")
            .Replace("center]\n", "center]")
            .Replace("li]\n", "li]")
            .Replace("ol]\n", "ol]")
            .Replace("ul]\n", "ul]")

            .Replace("h1]\r\n", "h1]")
            .Replace("h2]\r\n", "h2]")
            .Replace("h3]\r\n", "h3]")
            .Replace("h4]\r\n", "h4]")
            .Replace("h1]\n", "h1]")
            .Replace("h2]\n", "h2]")
            .Replace("h3]\n", "h3]")
            .Replace("h4]\n", "h4]")

            .Replace("\r\n[h1]", "[h1]")
            .Replace("\r\n[h2]", "[h2]")
            .Replace("\r\n[h3]", "[h3]")
            .Replace("\r\n[h4]", "[h4]")
            .Replace("\n[h1]", "[h1]")
            .Replace("\n[h2]", "[h2]")
            .Replace("\n[h3]", "[h3]")
            .Replace("\n[h4]", "[h4]")
            ;        

请注意

这只是这个过程的一个步骤。还有许多其他自定义标记,例如blue, red, email doc已经被解析为HTML。我试图删除换行符的原因是因为我无法使用换行符br标记。我们必须在文本文档中维护正常的换行符。

1 个答案:

答案 0 :(得分:0)

regx怎么样

((?:center|li|[ou]l|h[1-4])\])\r?\n|\r?\n(\[h[1-4]\])

替换捕获组1的内容

text = text.Replace("((?:center|li|[ou]l|h[1-4])\\])\\r?\\n|\\r?\\n(\\[h[1-4]\\])", "$1")