简体   繁体   中英

Matching CSS Selectors with a Javascript RegExp

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);

I would change it to a lazy star and try again:

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

That way it won't be greedy.

您是否尝试过用否定的字符类替换。*?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM