Regex to match any “UNUSED” rules in CSS (class, id, etc)

别说谁变了你拦得住时间么 提交于 2019-12-06 05:17:02
amiregelz

This Regex will match any UNUSED attribute: UNUSED.*\{[^}]*\}|UNUSED.*[}]*

The first part of the regex matches any UNUSED attribute that includes a block, and the second part of the regex (after the |) matches any UNUSED attribute that does not include a block - so you're totally covered. It will match classes, id's, blocks, single lines - every UNUSED attribute.

RegExr test


* jdlx's regex is a bit more complex but it's better and safer. Take a look at it.

jdlx

amiregelz's regex above will match rules with valid selectors.. thus break the CSS.
Here's my2¢ on regexing it :

Step 1 - match whole rules with only unused selectors and remove the whole rule:

(?<=}|/)\s*(UNUSED[.#:<>\+\w\d\s_-]+)(,\s*UNUSED[.#:<>\+\w\d\s_-]+)*\{[^\}]+}

Step 2 - match all unused selectors on rules that do have valid/used selectors:

(UNUSED[.#:<>\+\w\d\s_-]+,\s)|(,\s*UNUSED[.#:<>\+\w\d\s_-]+)

RegExr Tests: Step 1 - Step 2

hth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!