繁体   English   中英

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

[英]regular expression to match CSS “<property>: <value>”

我从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

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

我该如何实现这一目标?

提前致谢!

你可以把字符串分开;

document.getElementById(id).style.cssText.split(";")

编辑:

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

在此输入图像描述

编辑2:

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

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

代替

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

看到此深入研究:

在此输入图像描述

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

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

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

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

应该创建:

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

这会将它全部分解为命名项

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM