使用JavaScript RegExp匹配CSS选择器 [英] Matching CSS Selectors with a Javascript RegExp

查看:148
本文介绍了使用JavaScript RegExp匹配CSS选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要模式匹配CSS文件中的任何和所有CSS选择器。理想情况下,它应该能够捕获所有这些规则(和任何其他规则,有人可以在一个CSS文件中组成)。这是一个JavaScript CSS解析器,如果这有助于所有。

Basically I need to pattern match any and all CSS selectors in a CSS file. Ideally it should be able to grab all of these rules (and any other rule someone could make up in a CSS file). This is for a javascript CSS parser if that helps at all.

#div div .child {

}

.somediv, #someotherdiv {

}

body:hover {

}

到目前为止我能够想出的最好的例子是:

The best i've been able to come up with so far is something like:

/(#|\.|[a-zA-Z])(.*) {/g

但这只是最终选择超过它需要的...像一个选择器,所有它的规则,并到下一个选择器的开放 {。试了几个小时这个。提前感谢!

But this just ends up selecting more than what it needs to... Like one selector, all it's rules, and the up to the next selector's opening "{". Been trying for hours with this. Thanks in advance!

推荐答案

如果你只关心选择器本身,这应该让你更接近。我认为它是匹配单个空格,因此可以使用一些更多的调整...

If you're just concerned about the selectors themselves, this should get you a little closer. I think it is matching single spaces, so could use a little more tweaking yet...

var css = ...some css string...
var found = css.replace(/{([^}]*)}/gm,"{}").match(/([#|\.]?)([\w|:|\s|\.]+)/gmi);

这篇关于使用JavaScript RegExp匹配CSS选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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