python - 如何编写正则表达式以从 CSS 文件中提取特定的键格式和值?

标签 python css regex

我有一个由一些工具生成的 CSS 文件,它的格式如下:

@font-face {
    font-family: 'icomoon';
    src:url('fonts/icomoon.eot?4px1bm');
    src:url('fonts/icomoon.eot?#iefix4px1bm') format('embedded-opentype'),
        url('fonts/icomoon.woff?4px1bm') format('woff'),
        url('fonts/icomoon.ttf?4px1bm') format('truetype'),
        url('fonts/icomoon.svg?4px1bm#icomoon') format('svg');
    font-weight: normal;
    font-style: normal;
}

[class^="icon-"], [class*=" icon-"] {
    font-family: 'icomoon';
    speak: none;
    font-style: normal;
    font-weight: normal;
    font-variant: normal;
    text-transform: none;
    line-height: 1;

    /* Better Font Rendering =========== */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.icon-pya:before {
    content: "\e60d";
}
.icon-pyp:before {
    content: "\e60b";
}
.icon-tomb:before {
    content: "\e600";
}
.icon-right:before {
    content: "\e601";
}

我想在 Python 中使用正则表达式来提取每个以 .icon- 及其相关值开头的 CSS 选择器,例如:

{key: '.icon-right:before', value: 'content: "\e601";'}

我只有基本的正则表达式知识,所以我这样写:\^.icon.*\,但它只能匹配键,不能匹配值。

最佳答案

如果您使用的是 Python,则此正则表达式有效:

(\.icon-[^\{]*?)\s*\{\s*([^\}]*?)\s*\}

例子:

>>> css = """
... /* ... etc ... */
... .icon-right:before {
...     content: "\e601";
... }
... """
>>> import re
>>> pattern = re.compile(r"(\.icon-[^\{]*?)\s*\{\s*([^\}]*?)\s*\}")
>>> re.findall(pattern, css)
[
    ('.icon-pya:before', 'content: "\\e60d";'),
    ('.icon-pyp:before', 'content: "\\e60b";'),
    ('.icon-tomb:before', 'content: "\\e600";'),
    ('.icon-right:before', 'content: "\\e601";')
]

然后您可以轻松地将其转换为字典:

>>> dict(re.findall(pattern, css))
{
    '.icon-right:before': 'content: "\\e601";',
    '.icon-pya:before': 'content: "\\e60d";',
    '.icon-tomb:before': 'content: "\\e600";',
    '.icon-pyp:before': 'content: "\\e60b";'
}

这通常是比 {'key': ..., 'value': ...} 字典序列更明智的数据结构 - 如果你必须有后者,我'我们假设您有足够的 Python 来弄清楚如何获得它。

好吧,这是一个非常复杂的正则表达式,所以一点一点地看:

(\.icon-[^\{]*?)

这是第一个捕获组,由括号分隔。在这些里面,我们有 \.icon-,然后是 [^\{]*? - 这是一个 0 或更多的序列 (*) 但尽可能少 (?) 除了 '{' ([^\{])。

然后,有一个非捕获部分:

\s*\{\s*

这意味着任意数量的空格 (\s*),后跟一个 '{' (\{),然后是任意数量的空格 (\s*).

接下来,我们的第二个捕获组,再次括在括号中:

([^\}]*?)

... 0 或更多 (*) 但尽可能少 (?) 除了 '}' ([^\}]).

最后,最后一个非捕获部分:

\s*\}

...这是任意数量的空格 (\s*),后跟一个 '}' (\})。

如果您想知道,使用 *?(0 或更多但尽可能少 - 称为 非贪婪 匹配)的原因是这样的\s*(任意数量的空格)的匹配可以消耗尽可能多的空格,并且它不会在捕获的组内结束。

关于python - 如何编写正则表达式以从 CSS 文件中提取特定的键格式和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23966203/

相关文章:

python - 类型错误 : encoding without string argument

python - 如何计算同一列中的值

JQuery addClass() 和 removeClass() 同步

jquery toggle 表现得像隐藏而不是动画

javascript - 如果在移动设备上运行 jQuery

javascript - 不使用正则表达式匹配嵌套出现的情况

python - matplotlib 在 Python 中显示空图

python - 将字母转换为小写

python - 如何使用正则表达式解析化学式?

Python SHA256 哈希计算