正则表达式减去类名,我的错误是什么?

时间:2015-09-26 02:21:13

标签: javascript regex

如果CSS规则包含某些属性,我正在尝试编写一个正则表达式,该正则表达式将从CSS规则中删除一个类名(通过捕获组)。

例如:

.myClass

如果specialProp具有属性.myClass(在此示例中就是这种情况),则从CSS规则结构中减去test.match(/(\.\w*)(?=\s*{[^]+specialProp:[^]+})/); ,但包含该属性的类的类名。 我试过这个,它使用正向前瞻

specialProp

它有用,但如果属性system/app包含在任何类中,它将匹配所有类名。

如果字符串上还有其他类名,我怎样才能使它只匹配包含特殊属性的类名?我想我可以想到另一种实现相同目标的方法,但我觉得我很接近正则表达式解决方案。

谢谢。

3 个答案:

答案 0 :(得分:0)

如果您将\s*.*替换为[\s\S]*,则会获得multiline match

但总的来说,这不是一个很好的方法。 如果该属性名称作为其他文本的一部分出现在类规则中,该怎么办? 例如:

var test = `
    .myClass {
        background: http://example.com/specialProp:/image.gif;
    }

    .secondClass {
        content: 'specialProp:';
    }
`;

正则表达式太低,无法进行此类检查。

此外,多行正则表达式不知道一个类主体何时结束而下一个类主体何时开始。 找到与正则表达式的边界是非平凡的。

如果要查询已经解析过的浏览器,请更好地解析CSS existing the JavaScript CSS parser或使用CSS DOM

答案 1 :(得分:0)

您可以使用CSS功能检测

  

@supports< condition> {/ *规则* /}

例如:

@supports (text-shadow: 0 0 5px #000) { .blur-text { color:
 transparent; text-shadow: 0 0 5px #000; } }

参考:http://www.sitepoint.com/supports-native-css-feature-detection/

但并非所有浏览器都支持:ref:http://caniuse.com/#search=%40support

我的建议是使用像Stylus或更少的CSS预处理器。

答案 2 :(得分:0)

要匹配包含property:的CSS规则,请使用?修饰符在结束括号之前进行最短匹配{[^}]*?

/\.\w+\s*{[^}]*?property:[^}]*?}/

更一般地说:

new RegExp('\\.\\w+\\s*{[^}]*?' + property + ':[^}]*?}');

以下代码段演示了这种方法:



function removeClassWithProperty(property, text) {
  var re = new RegExp('\\.\\w+\\s*{[^}]*?' + property + ':[^}]*?}');
  return text.replace(re, '');
}

function print(s) {
  document.write(s + '<br><br>');
}

var test = `
    .myUglyClass {
        propOne: abc;
        notSpecialProp: def;
        propThree: ghi;
    }
    .myClass {
        propOne: abc;
        specialProp: def;
        propThree: ghi;
    }
`;

print(removeClassWithProperty('fakeProperty', test));

print(removeClassWithProperty('specialProp', test));

print(removeClassWithProperty('propThree', test));
&#13;
body {
  font-family: sans-serif;
}
&#13;
&#13;
&#13;

相关问题