【问题标题】:RegEx to minimize CSS正则表达式最小化 CSS
【发布时间】:2011-05-23 01:55:30
【问题描述】:

我有一个我用 node.js 编写的海峡前向聚合器/最小化器/缓存器。它现在工作得很好。

然而,我想知道是否有任何方法可以改善我的最小化正则表达式调用。一些 cmets 没有完全从 CSS 中分离出来,我注意到这里和那里还有一些其他问题。

另外,考虑到我在正则表达式方面的能力,我也许可以在一半的调用中做同样的事情。 :)

任何建议将不胜感激。

谢谢。

function minimizeData( _content ) {
    var content = _content;
    content = content.replace( /(\/\*.*\*\/)|(\n|\r)+|\t*/g, '' );
    content = content.replace( /\s{2,}/g, ' ' );
    content = content.replace( /(\s)*:(\s)*/g, ':' );
    content = content.replace( /(\s)+\./g, ' .' );
    content = content.replace( /(\s|\n|\r)*\{(\s|\n|\r)*/g, '{' );
    content = content.replace( /(\s|\n|\r)*\}(\s|\n|\r)*/g, '}' );
    content = content.replace( /;(\s)+/g, ';' );
    content = content.replace( /,(\s)+/g, ',' );
    content = content.replace( /(\s)+!/g, '!' );
    return content;
}

【问题讨论】:

    标签: javascript css regex node.js minimize


    【解决方案1】:
    function minimizeData( _content ) {
        var content = _content;
        content = content.replace( /\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g, '' );
        // now all comments, newlines and tabs have been removed
        content = content.replace( / {2,}/g, ' ' );
        // now there are no more than single adjacent spaces left
        // now unnecessary: content = content.replace( /(\s)+\./g, ' .' );
        content = content.replace( / ([{:}]) /g, '$1' );
        content = content.replace( /([;,]) /g, '$1' );
        content = content.replace( / !/g, '!' );
        return content;
    }
    

    应该更清晰一些,避免重复。第一次替换后,将只剩下空格;第二次替换后,只有一个空格。这使得以下替换更容易。

    解释删除注释的正则表达式(此处显示为没有分隔符的纯详细正则表达式):

    /\*       # Match /*
    (?:       # Match (any number of times)...
     (?!\*/)  # ... as long as we're not right before a */:
     [\s\S]   # any character (whitespace or non-whitespace).
    )*        # (End of repeated non-capturing group)
    \*/       # Match */
    

    【讨论】:

    • 谢谢,这已经改进了很多。但是,一些 cmets 仍然没有被解析。一个的粘贴是 /* Interaction Cues---------------------------------*/ Thoughts?
    • position:absolute;opacity:0;filter:Alpha(Opacity=0);}/* 交互线索-------------------- --------------*/.ui-state-disabled{cursor:default!important;}
    • 这可能是第一个正则表达式中的|[\r\n\t]*。它匹配}/ 之间的空值,然后正则表达式引擎在零长度匹配后向前移动一个位置,因此它试图匹配从 after 开始的评论斜线。 |[\r\n\t]* 无论如何都不应该在那里;我会摆脱它并将第二个正则表达式更改为/\s+/g
    • @Alan 做到了!谢谢楼主!
    • @350D 我在content = content.replace( / ([{:}]) /g, '$1' );之后添加了这一行content = content.replace( /([{:}]) /g, '$1' );
    猜你喜欢
    • 2015-12-26
    • 2019-03-26
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    相关资源
    最近更新 更多