正则表达式缩小<pre> tag content</pre>

时间:2013-06-01 17:09:18

标签: c# regex minify

我正在使用this filter来缩小我的HTML。不幸的是,该过滤器还会缩小<pre>标记内的代码,但我不希望它们被更改。我如何更改正则表达式,以便它们不会缩小<pre>标记内的任何代码?

s = Regex.Replace(s, @"\s+", " ");
s = Regex.Replace(s, @"\s*\n\s*", "\n");
s = Regex.Replace(s, @"\s*\>\s*\<\s*", "><");
s = Regex.Replace(s, @"<!--(.*?)-->", "");   //Remove comments

1 个答案:

答案 0 :(得分:3)

在该过滤器的开发人员提供此选项之前,您可以尝试以下操作:您可以向正则表达式添加嵌套lookahead assertion,以阻止它们匹配</pre>标记(除非{{ {1}}标签首先出现)。对于前三个正则表达式,这意味着:

<pre>
前瞻断言的

解释

s = Regex.Replace(s, @"(?s)\s+(?!(?:(?!</?pre\b).)*</pre>)", " ");
s = Regex.Replace(s, @"(?s)\s*\n\s*(?!(?:(?!</?pre\b).)*</pre>)", "\n");
s = Regex.Replace(s, @"(?s)\s*\>\s*\<\s*(?!(?:(?!</?pre\b).)*</pre>)", "><");

对于第四个正则表达式,我们必须首先确保(?! # Assert that the following regex can't be matched here: (?: # Match... (?! # (unless the following can be matched: </?pre\b # an opening or closing <pre> tag) ) # (End of inner lookahead assertion) . # ...any character (the (?s) makes sure that this includes newlines) )* # Repeat any number of times </pre> # Match a closing <pre> tag ) # (End of outer lookahead assertion) 与任何.*?标记都不匹配

<pre>

除此之外,正则表达式的工作方式如上所述。