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 {
}
bo开发者_StackOverflowdy: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);
I would change it to a lazy star and try again:
/(#|\.|[a-zA-Z])(.*?) {/g
That way it won't be greedy.
In order to do brace-matching, you need a language more descriptive than what plain old regex provides. http://www.regular-expressions.info/named.html has some examples of what different programming languages have come up with to deal with the "named group" problem.
You'll need a parser, not just regex for what you're doing.
Have you tried replacing .* with negated character class?
/(#|\.|[a-zA-Z])([^{]*) {/g
精彩评论