我想用Boost.Spirit来解析嵌套列表的数字。这是我到目前为止有:用Boost.Spirit解析嵌套列表
//define a test string
std::string string = "[[\t1 , 2 ], [3, 4, 65.4]]";
auto it = string.begin();
//parse the string
std::vector<std::vector<double>> vector;
auto listRule = "[" >> (qi::double_ % ",") >> "]";
auto list2Rule = "[" >> (listRule % ",") >> "]";
bool match = qi::phrase_parse(it, string.end(), list2Rule, ascii::space, vector);
//check if we have a match
std::cout << "matched: " << std::boolalpha << match << '\n';
if (it != string.end())
std::cout << "unmatched part: " << std::string{it, string.end()} << '\n';
//print the result
std::cout << "result\n";
for (const auto& v : vector) {
std::cout << "[";
for (double i : v)
std::cout << i << ",";
std::cout << "]\n";
}
以上奇妙的作品和版画:
matched: true
result
[1,2,]
[3,4,65.4,]
我现在面临的问题是,它不接受空名单。例如,通过改变字符串像这样:
std::string string = "[[\t1 , 2 ], [3, 4, 65.4], []]";
然后我不匹配(即match == false
和it == string.begin()
)。显然,该矢量仍然被填充,但最后一个空列表丢失。任何人都可以提供解释,为什么这是这种情况,以及如何解决它?
的''%解析器被定义为:“列表。解析一个或多个分隔符b“。IIRC,你可以简单地将列表标记为可选项,并且它会做你想做的事情:'”[“>> - (listRule%”,“)>>”]“; ' – Frank
Uhmm .. nope,似乎不起作用。在这种情况下(和'listRule'和'list2Rule'中的所有组合一起,我得到一个载体列表,每个载体只有一个值... – matpen