2
我想写一个小的代码分析器来分析嵌套结构并将其翻译为有效的CSS
。但是,我没有保留从上层继承的标识符。解析嵌套的CSS结构
嵌套结构:
#foo {
border: 1px;
a {
border: 2px;
}
b {
border: 3px;
c {
border: 4px; /* comment */
}
}
}
我想结构翻译成:
#foo {
border: 1px;
}
#foo a {
border: 2px;
}
#foo b {
border: 3px;
}
#foo b c {
border: 4px; /* comment */
}
解析代码:
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main() {
string str = "\
#foo {\
border: 1px;\
a {\
border: 2px;\
}\
b {\
border: 3px;\
c {\
border: 4px; /* comment */\
}\
}\
}";
string::const_iterator i = str.end(),
begin = str.begin(), end;
while (i != begin) {
if (*i == ';' || (*i == '/' && *(i-1) == '*')) {
end = i++;
while (*i-- != '{');
while (true) {
if (*i == ';' || *i == '}' || *i == '{' || i == begin)
break;
i--;
}
string item(++i, ++end);
cout << item << "}" << endl;
}
i--;
}
return 0;
}
日期:
c {
border: 4px; /* comment */
}
b {
border: 3px;
}
a {
border: 2px;
}
#foo {
border: 1px;
}
那么,如何保留从上层继承的标识符呢?
如果你不这样做纯粹是作为一个练习的时候,意识到已经有东西在那里像[LESS CSS(http://lesscss.org/)这是做什么的。 – icktoofay 2012-01-29 09:02:40
@icktoofay,我知道'LESS'非常好,我想用C++来做这件事。嵌套规则是唯一需要做的事 – 2012-01-29 09:07:24
您可以将标识符保留在堆栈中。当你沿着层次结构向上/向下时,你推/拉弹出。 – Alexander 2012-01-31 11:58:51