0

我需要解析一段 CSS。例子:

<style ...>
.foo , #bar {
   /*some css code here*/
   background-image: url(image.png);
 }

 p { 
   background: url(image2.png) repeat-x;
   font-size: 1em;
 }

 a {
   font-size: 1.1em;
 }

</style>

我想将其转换为以下数组:

[
 {"selector":".foo , #bar", "bg":"image.png"},
 {"selector":"p", "bg":"image2.png"}
]

我有兴趣匹配 url(IMAGE),然后获取它的选择器。

4

2 回答 2

0

使用JSCSSP

CSS

<textArea id="source"></textArea>
<button id="parse">Parse</button>

Javascript

var source = document.getElementById("source"),
    ss,
    parser,
    sheet,
    length1,
    index1,
    length2,
    index2,
    myArray,
    cssRule,
    declaration,
    selector,
    bg;

document.getElementById("parse").addEventListener("click", function () {
    ss = source.value;
    parser = new CSSParser();
    sheet = parser.parse(ss, false, true);

    if (sheet) {
        myArray = [];
        for (index1 = 0, length1 = sheet.cssRules.length; index1 < length1; index1 += 1) {
            cssRule = sheet.cssRules[index1];
            selector = cssRule.mSelectorText;
            for (index2 = 0, length2 = cssRule.declarations.length; index2 < length2; index2 += 1) {
                declaration = cssRule.declarations[index2];
                if (declaration.property === "background-image") {
                    bg = declaration.valueText.match(/url\((\S+)\)/i)[1];
                    myArray.push({
                        "selector": selector,
                        "bg": bg
                    });

                    break
                }
            }
        }

        console.log(myArray);
    }
});

jsfiddle

于 2013-09-30T09:12:13.927 回答
0
(?<selector>\n.*?)[^{}](\{.+?(?<=url\()(?<image>[^\)]*).+?\})

在您的<script>块上发布将为您提供一个具有 2 个命名组的正则表达式

regex.groups("selector") = ".foo, #bar"
regex.groups("image") = "image.png"

第二场比赛

regex.groups("selector") = "P"
regex.groups("image") = "image2.png"

或者你可以在你的正则表达式中使用“image.png”来获得:

\n(?<selector>[^{]*?){(?<t>.+)(?<image>image.png)

得到结果

regex.groups("selector") = ".foo, #bar"
于 2013-09-30T09:12:26.900 回答