【问题标题】:How to parse a structured format?如何解析结构化格式?
【发布时间】:2011-12-25 19:27:33
【问题描述】:

我有一个字符串,我想在结构块上解析它。

所以,字符串结构如下:

if(true) {
    if(true) {
        if(true) {}
    }
}
if(true) {
    if(true) {
        if(true) {}
    }
}

我想像这样在父块上拆分一个:

if(true) {
    if(true) {
        if(true) {}
    }
},

if(true) {
    if(true) {
        if(true) {}
    }
}

我的代码:

string condition = 
"if(true) {\
    if(true) {\
        if(true) {}\
    }\
}\
if(true) {\
    if(true) {\
        if(true) {}\
    }\
}";

string item; 
stringstream stream(condition);
vector<string> array;

//splitting on sections
while (getline(stream, item, '}')) {
    array.push_back(item + "}");
}

for(int i = 0; i < array.size(); i++) {
    cout << i << array[i] << endl;
}

结果:

0 if(true) { if(true) { if(true) {}
1   }
2 }
3 if(true) { if(true) { if(true) {}
4   }
5 }

但需要:

0 if(true) { if(true) { if(true) {} } }
1 if(true) { if(true) { if(true) {} } }

如何更正确地检测和解析父块或告诉算法?

【问题讨论】:

  • 好像要拆分字符串?如果这是真的,看看这里的一些解决方案:stackoverflow.com/questions/236129/how-to-split-a-string-in-c
  • 谢谢,我已经看过那篇文章,但我有一个稍微不同的问题。我不懂要解析的算法。
  • @AlexanderGuiness:您可能想研究 Boost.Spirit 以进行一些高功能解析。
  • @GMan,我不想为此安装额外的库,而是想做一个简单的算法。

标签: c++ parsing stl token


【解决方案1】:

您需要计算当前的深度。我发现最好的解析器是基于迭代器的,所以这就是我将在这里展示的内容。 std::getline 对解析不是很有用,除非是最简单的格式。

完全未经测试的代码:

std::vector<std::string> vec;

int depth = 0;
std::string::const_iterator first = condition.begin(),
                            last = condition.end(),
                            iter = first;

for(;;)
{
    iter = std::find_if(iter, last,
                        [](char ch) { return ch == '{' || ch == '}'; });

    if(iter == last)
    {
        if(depth)
        {
            throw std::runtime_error("unclosed block found.");
        }

        break;
    }

    if(*iter == '{')
    {
        ++depth;
        ++iter;
    }
    else if(*iter == '}' && !--depth)
    {
        v.push_back(std::string(first, ++iter));
        first = iter;
    }
    else
    {
        ++iter;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 2021-12-14
    • 2017-08-30
    • 2015-09-14
    • 2016-02-02
    相关资源
    最近更新 更多