正则表达式用于选择没有特定颜色值的 CSS 声明块



假设我有以下CSS。我需要一个正则表达式来获取中不包含以下颜色的整个声明块(选择器、左括号、内容、右括号(:#f518e2#22f1e6

.foo{
color: #f518e2;
box-spacing: border-box;
}
#bar{
color: #e4e4e4;
box-spacing: border-box;
}
biz.baz{
background: #22f1e6;
font-size: 30px;
}

所以在这种情况下,我想获取:

#bar{
color: #e4e4e4;
box-spacing: border-box;
}

假设:

  • 文件中有数百个选择器
  • 语法始终是有效的CSS,但间距、新行和分号的使用不一致。例如:
#bar{   color: #e4e4e4;   
box-spacing: border-box; }biz.baz
{   
background: #22f1e6;   
font-size: 30px; }

我尝试过这样的方法:/w*[#.]?w+s*{[^{}]+}/g,它选择整个声明块,但当要剔除带有#f518e2#22f1e6的块时,它有点超出了我对regex的了解。

一个选项可以是匹配{位于行首、}位于行尾的所有行,并使用负前瞻匹配其间没有#f518e2#22f1e6的所有行。

请注意,此模式适用于给定的示例,但不考虑任何嵌套或数据结构。

^.*{(?:r?n(?!.*#(?:f518e2|22f1e6)b).*)*r?n}

模式匹配:

  • ^字符串开始
  • .*{整行匹配,{末尾匹配
  • (?:非捕获组
    • r?n匹配换行符
    • (?!.*#(?:f518e2|22f1e6)b).*断言该行不包含颜色并与整行匹配
  • )*关闭非捕获组并重复0+次
  • r?n匹配换行符
  • }匹配{

Regex演示

您可能想要使用JavaScript来完成这样的任务。我为你的研究提供了一个例子:

//<[CDATA[
/* js/external.js */
function hexNum(x){
switch(x.toUpperCase()){
case 'A':
return 10;
case 'B':
return 11;
case 'C':
return 12;
case 'D':
return 13;
case 'E':
return 14;
case 'F':
return 15;
default:
return +x;
}
}
function hexToRGBArray(hex){
let s, r = [];
if(hex.match(/^#?[dA-F]{6}$/i)){
s = hex.replace(/^#/, '').split('');
for(let i=0,q=1; i<6; i+=2,q+=2){
r.push(hexNum(s[i])*16+hexNum(s[q]));
}
}
else if(hex.match(/^#?[dA-F]{3}/i)){
s = hex.replace(/^#/, '').split('');
for(let i=0,h; i<3; i++){
h = hexNum(s[i]); r.push(h*16+h);
}
}
else{
throw new Error('invalid hexadecimal');
}
return r;
}
addEventListener('load', ()=>{
// stack overflow is including nodes you won't see in real world
const all = document.body.querySelectorAll('*');
const avoid1 = hexToRGBArray('#f518e2').join(), avoid2 = hexToRGBArray('#22f1e6').join();
let s;
for(let n of all){ // n being node
s = getComputedStyle(n).color.replace(/^.+(|).*$/g, '').split(/s*,s*/).join();
if(s !== avoid1 && s !== avoid2){
console.log(n.textContent);
// n is node
}
}
}); // end load
//]]>
/* css/external.css */
div{
color:#ab7722;
}
#test1{
color:#f518e2;
}
#test4{
color:#22f1e6;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div id='test1'>nope</div>
<div id='test2'>got this one</div>
<div id='test3'>and this one</div>
<div id='test4'>not this one</div>
</body>
</html>

注意,在现实世界中,CCD_ 20将仅访问CCD_。堆栈溢出必须考虑其他因素。他们应该修复它。

最新更新