【问题标题】:Regex minify <pre> tag content正则表达式缩小 <pre> 标签内容
【发布时间】:2013-05-28 07:51:29
【问题描述】:

我正在使用this filter 来缩小我的 HTML。不幸的是,该过滤器还缩小了&lt;pre&gt; 标签内的代码,但我不希望它们被更改。如何更改正则表达式,使其不会缩小 &lt;pre&gt; 标签内的任何代码?

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

【问题讨论】:

  • 你联系过创作者吗?还是在他们的网站上留下了同样问题的评论?

标签: c# regex minify


【解决方案1】:

在该过滤器的开发人员提供此选项之前,您可以尝试以下操作:您可以将嵌套的 lookahead assertion 添加到您的正则表达式中,以防止它们在出现 &lt;/pre&gt; 标记时匹配(除非出现 &lt;pre&gt; 标记第一的)。对于前三个正则表达式,这意味着:

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)

对于第四个正则表达式,我们必须首先确保.*? 也不匹配任何&lt;pre&gt; 标签

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    相关资源
    最近更新 更多