Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find CSS class names that are not inside comments using Regular Expressions

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; }
table.simple{background:#fff;}.bg-white{background:#fff;}
/*# sourceMappingURL=style.css.map */
/*
Example comment file.css
*/

the result is:

.a { text-align: center; }
table.a{background:#fff;}.a{background:#fff;}
/*# sourceMappingURL=style.a.a */
/*
Example comment file.a
*/

what I want is:

.a { text-align: center; }
table.a{background:#fff;}.a{background:#fff;}
/*# sourceMappingURL=style.css.map */
/*
Example comment file.css
*/

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

like image 552
mbrandau Avatar asked Feb 23 '26 18:02

mbrandau


1 Answers

Try this regex:

\.[^{\s]*(?=\s*{)

and replace each match with .a

Click for Demo

Explanation:

  • \. - matches a .
  • [^{\n]* - matches 0+ occurrences of any character that is neither a white-space nor {
  • (?=\s*{) - positive lookahead to make sure that the current position is followed by 0+ whitespaces followed by {.

Now, the above regex would fail if we have comments of the format

/*# sourceMappingURL=style.css.map {*/

i.e, { present after css.map inside a comment. So, to handle such a case, you can use the following regex(almost similar to the previous regex. Just one more negative lookahead to the regex)

\.[^{\s]*(?=\s*{)(?!(?:(?!\/\*)[\s\S])*\*\/)

Click for Demo

Explanation:

  • \.[^{\s]*(?=\s*{) - similar to the previous regex
  • (?!(?:(?!\/\*)[\s\S])*\*\/) - Negative lookahead to make sure that the current position(position right after the .classname) is not present within a comment of the form /*...*/
    • (?!.... - negative lookahead
    • (?:(?!\/\*)[\s\S])* - tempered greedy token to match 0+ occurrences of any character greedily, which does not begin with the sequence /*
    • \*\/ - matches */
like image 51
Gurmanjot Singh Avatar answered Feb 26 '26 10:02

Gurmanjot Singh