【问题标题】:What is RegEx to remove css keeping font size [closed]什么是 RegEx 删除 css 保持字体大小 [关闭]
【发布时间】:2013-06-29 05:28:07
【问题描述】:

我有一个大的 css 文件,我需要从中删除除选择器和字体大小属性以及花括号之外的所有规则。 RegEx 会选择其他所有内容吗?

文件的格式几乎是这样的。

.details h2 {margin: -14px 0 0 0; padding: 0 20px 24px 20px; font-size: 12px; color: #474747;}

我需要它以这样的方式结束。

.details h2 {font-size: 12px;}

【问题讨论】:

  • 文件的格式如何?它是否在同一行有多个属性,是否在花括号等的同一行有属性?
  • 你用什么语言做这个?到目前为止,您尝试过什么?
  • 发布您的一些代码。看看它是如何格式化的。
  • 请张贴您想要保留的 CSS 部分的示例
  • 这可能会有所帮助。这里引用了一些 CSS 解析器:stackoverflow.com/questions/236979/parsing-css-by-regex

标签: css regex


【解决方案1】:

我可以使用 Sublime Text:

Find: \{.*(font-size\:\s*\d+px\;).*\}?
Replace: \{ $1 \}

如果 css 被拆分为多行(应该是 ;)),那么它需要更多的努力。好吧,我可能会考虑两个或三个单独的替换操作。

【讨论】:

  • 当然,字体大小可能并不总是以像素为单位。
  • @JustinS,请记住,font-size 可能会以像素以外的形式指定,并且(如该答案所述),多行规则将是一个问题。如果 Andy 的解决方案满足您的需求,您可以随时使用功能更强大的搜索 \{.*(font-size:\s*[^;}]).*\}。对于跨越多行的解决方案,请参阅我的解决方案。
【解决方案2】:

嗯,要做到这一点 100% 铁定,您可能必须编写一个 CSS 解析器,这可不是在公园散步。但是,对于大多数情况,您可以使用正则表达式解决此问题。真正的关键是不要尝试在单个正则表达式中做太多事情(一个常见的错误)。我的解决方案涉及两个独立的正则表达式:一个解析规则,另一个从声明块中选择“字体大小”声明。你没有说你有什么语言或工具可用,但我用 JavaScript 实现了这个:

var css = $('style').text();   // this will grab the CSS of the page it's on...you can
                               // use whatever CSS you want, of course; this is just
                               // a string containing CSS

// join all lines by removing carriage returns; otherwise we'll run into
// lots of problems trying to grok rules that span multiple lines
css = css.replace( /\n/g, '' );

// match all rules, and separate into selectors and declarations
css = css.replace(/\s*([^{]*)\s*\{(.*?)\}/g, function(match,selector,declarations) {
    // see if font-size is among the declarations; if so, capture it's value
    var fsMatch = declarations.match( /\bfont-size\s*:\s*([^;]+?)\s*(;|$)/i );
    // if font-size is present, return only that declaration, otherwise return empty
    return fsMatch ?
        selector + ' { font-size: ' + fsMatch[1] + '; }\n' :
        '';
});

// now the 'css' variable contains the CSS you're looking for

请注意,此解决方案也可以生成看起来非常干净的 CSS。

在此处查看实时示例:

http://jsfiddle.net/yLjCe/2/

【讨论】:

    猜你喜欢
    • 2018-12-08
    • 2011-10-11
    • 2010-09-13
    • 2011-09-02
    • 2012-03-12
    • 2012-05-04
    • 2015-08-07
    • 2022-11-17
    • 2018-03-30
    相关资源
    最近更新 更多