There a quick way to add prefixes to all CSS class

2019-03-30 18:24发布

问题:

I need to quickly add prefixes to all of of my classes and ID's and it's quite a large CSS file. I was thinking a quick regex string but so far I've failed. Any ideas?

I've tried simple things like:

\#([A-z0-9]+) {

Which will let me replace with #prefix_$1 but it doesn't take into account:

#id {
#id.class
#id,

etc. I can't just replace all #[a-z0-9] because it will attempt to grab background-colors and so on.

I also need to replace all the classes, which is even more confusing for me.

回答1:

You could search:

\.(-?[_a-zA-Z]+[_a-zA-Z0-9-]*)[^}]+{

\#(-?[_a-zA-Z]+[_a-zA-Z0-9-]*)[^}]+{

Should find all your class names and id names

With RegExr, use this:

(?<=#|\.)(-?[_a-zA-Z]+[_a-zA-Z0-9-]*)(?=[^}]+{)

Edit: Here's a link to a test on google's CSS http://regexr.com?2ugv1



回答2:

You could try this [#|\.][\w]+\.?([\w\-]+\s?) it worked on these

#id {
#id.class {
#id, #otherId {
#class-dashed
#class_dashed
ul li:after {content: " #id.class { ";}
.class {background-color:     #fff250}
#id.class {color:#ff}

Also found a good tool to play around with different options. There will still be a problem with the colors, but you can't really get rid of that since they follow the same rules as the ids.

update excluding the : from the results to not match colours.

(?<![: ])[#\.][\w]+\.?([\w-]+\s?) you'll need a regex engine that supports negative lookbehind, not that familiar with php so don't know if it has it, but I would imagine it does.



回答3:

I'd go with something like this:

/([#\.])([^\d][a-z0-9-_]+)/ Replace with
$1PREFIX_$2

However beware that it would catch colors as well, (if done with lowercase letters) I'm working on a workaround right now.