正则表达式匹配CSS“<property>:<value>”</value> </property>

时间:2011-10-06 19:09:08

标签: javascript regex

我从document.styleSheets检索了CSS规则,现在正在寻找它的属性和值。

cssText = ".expl { position: absolute; background-color: rgb(204, 204, 204); max-width: 150px; }";

正则表达式是否可以在匹配中检索属性及其适当的值?另外,去掉尾随的分号。

我想得到如下结果:

position: absolute // match 1
background-color: rgb(204, 204, 204) // match 2
max-width: 150px // match 3

我只是提到我正在提取括号内的内容:(?<={)(.*)(?=}),我不知道应该继续做什么。

我如何实现这一目标?

提前致谢!

4 个答案:

答案 0 :(得分:4)

您可以在;

上拆分字符串
document.getElementById(id).style.cssText.split(";")

编辑:

请注意,样式对象的cssText属性不包含选择器

enter image description here

编辑2:

好的我做了一点挖掘,看来你从CSSStyleRule对象得到了你的cssText属性。这包括选择器。您可以通过更多树遍历获得以分号分隔的实际规则列表。您可以使用

获取样式对象
document.styleSheets[1].cssRules[0].style.cssText;

而不是

document.styleSheets[1].cssRules[0].cssText;

请参阅此深入研究:

enter image description here

答案 1 :(得分:3)

在括号之间拉出所有内容,然后将其拆分出来:

matches = cssrule.match(/{([^}]+)}/;
rules = matches[1].split(';');

答案 2 :(得分:2)

我的正则表达式有点生疏,但有点像:

var arr = cssText.replace(/\s/g,'')
                 .replace(/^.*{([^}]+)}.*/,'$1')
                 .match(/([^;]+)/g);

应该创建:

["position:absolute","background-color:rgb(204,204,204)","max-width:150px"]

答案 3 :(得分:0)

这将全部分解为命名项目

\s*(?<rule>(?<selector>[^{}]+){(?<style>[^{};]+:[^{};]+;\s*)+})

如果你的解析器不支持命名组(javascript不支持)从正则表达式中删除?<text>,就像这样

\s*(([^{}]+){([^{};]+:[^{};]+;\s*)+})

由于您的cssText可能不包含css选择器,您可能只想在;上拆分。如果没有,这对于解析样式表非常有用。我在我写入内联样式表的工具中使用它。