Home Find CSS class names that are not inside comments using RegEx
Reply: 2

Find CSS class names that are not inside comments using RegEx

mbrandau Published in 2018-02-12 19:29:59Z

I'm trying to replace all class names in a CSS file. I am using JavaScript/Node.js.

My current solution is this: /\.[a-z][a-z0-9-_]*/g. At the end of the file is a comment that references the source map file: /*# sourceMappingURL=style.css.map */. Now the file extensions of that URL also get replaced.

Given the following input:

.text-center { text-align: center; }
/*# sourceMappingURL=style.css.map */

the result is:

.a { text-align: center; }
/*# sourceMappingURL=style.a.a */

what I want is:

.a { text-align: center; }
/*# sourceMappingURL=style.css.map */

How do I have to change my RegEx so it does only match class names, that are outside of comments (// comments are not relevant here)?

Yanet Pedraza
Yanet Pedraza Reply to 2018-02-12 23:03:25Z

With the following regex you should be able to extract all class-names from your css file, which are not in comment. It´s important that the class name start with a dot (.)



mbrandau Reply to 2018-02-19 10:47:47Z

I've got it to work with the following RegEx in pcre flavor


I'm using a conditional statement. Whenever it detects a start of a comment, it does not look for a class name but for the end of the comment. However, this does not work for comments on multiple lines. The class names are the third capturing group. So to replace class names, only touch matches that contain the capturing group 3.

I didn't notice I was using pcre instead of javascript on regex101.com and ended up with a syntax error in my JS code. I'm now working on finding a solution that works for JS.


I now ported it to JS:


I still have to find a way to get it to work with multiple lines.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.303671 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO