2

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!

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

This worked awesomely. All I had to add was a quick "{" at the end it it's working. Thanks a bunch, man.
1

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

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

That way it won't be greedy.

1 Comment

This isn't the regex that I need, but your lazy star helped with another regexp I had to make. So +1 for you sir!
0

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.

Comments

0

Have you tried replacing .* with negated character class?

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.