1

我正在使用这个过滤器来缩小我的 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
4

1 回答 1

3

在该过滤器的开发人员提供此选项之前,您可以尝试以下操作:您可以向您的正则表达式添加一个嵌套的前瞻断言,如果后面跟着标签,则阻止它们匹配</pre>(除非<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>标签

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

除此之外,正则表达式的工作方式与上述相同。

于 2013-06-01T20:31:03.767 回答