Parsing CSS by regex

That just seems too convoluted for a single regular expression. Well, I’m sure that with the right extentions, an advanced user could create the right regex. But then you’d need an even more advanced user to debug it.

Instead, I’d suggest using a regex to pull out the pieces, and then tokenising each piece separately. e.g.,

/([^{])\s*\{\s*([^}]*?)\s*}/

Then you end up with the selector and the attributes in separate fields, and then split those up. (Even the selector will be fun to parse.) Note that even this will have pains if }’s can appear inside quotes or something. You could, again, convolute the heck out of it to avoid that, but it’s probably even better to avoid regex’s altogether here, and handle it by parsing one field at a time, perhaps by using a recursive-descent parser or yacc/bison or whatever.

Leave a Comment