RegEx只从CSS文件中提取选择器? [英] RegEx to extract only selectors from CSS file?

查看:229
本文介绍了RegEx只从CSS文件中提取选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个正则表达式,让我从CSS文件中提取 JUST 规则。我不想要任何样式声明,只是规则(选择器)。这里是我使用的示例CSS文件:

I'm trying to find a regular expression that will let me extract JUST the rules from a CSS file. I don't want any of the style declarations, simply the rules (selectors). Here's the sample CSS file I'm working with:

body, p, table, td, th, br, div, span {
    /* Some styles here */
}

/* This is a test */
h1 {
    /* Some styles here */
}

a:hover {
    /* Some styles here */
}

-moz-any(input[type="text"], input[type="radio"]) {
    /* Some styles here */
}

在这个例子中,我期望我的正则表达式匹配以下项目:body,p,table,td,th,br,div,span,h1,a:hover,-moz-any (输入[type =text],输入[type =radio])

In this example I would expect my regular expression to match the following items: body, p, table, td, th, br, div, span, h1, a:hover, -moz-any(input[type="text"], input[type="radio"])

这是我尝试正则表达式。虽然它工作,它包括/ *这是一个测试* /注释,它还包括大括号。理想地,将省略那些。

Here's my attempt at the regular expression. While it works, it includes the /* This is a test */ comment and it also includes the curly braces. Ideally those would be omitted.

(}{0,})([^}]*)({)

任何帮助将非常感谢。非常感谢!

Any help with this would be greatly appreciated. Many thanks in advance!

我还应该注意,我明白这不是一个伟大的CSS文件。它只是一个测试文件,我想出来测试我的解析。

I should also note that I understand this isn't a great CSS file. It's simply a test file I came up with to test my parsing with.

推荐答案

我不能得到一个解决方案使用RegEx ,所以我遵循Qtax的建议,并使用一个适当的解析器与CSS3语法。

I was not able to get a solution using RegEx, so I followed Qtax's advice and used a proper parser with CSS3 grammar.

我将此问题标记为答案。

I am marking this question as the answer.

@Qtax - 如果您将评论添加为答案,我会将其标记为正确答案:)

@Qtax - If you add your comment as an answer, I'll mark that as the "correct" answer :)

这篇关于RegEx只从CSS文件中提取选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆