gpt4 book ai didi

c++ - Boost精神太贪心

转载 作者:可可西里 更新时间:2023-11-01 17:39:44 27 4
gpt4 key购买 nike

我介于对 boost::spirit 的深深钦佩和不理解它的永恒挫折之间;)

我的字符串过于贪婪,因此不匹配。下面是一个不解析的最小示例,因为 txt 规则吃完了。

有关我想做的事情的更多信息:目标是解析一些伪 SQL,我跳过空格。在类似

的声明中
select foo.id, bar.id from foo, baz 

我需要将 from 视为特殊关键字。规则类似于

"select" >> txt % ',' >> "from" >> txt % ',' 

但它显然不起作用,因为它将 foo 的 bar.id 视为一个项目。

#include <boost/spirit/include/qi.hpp>
#include <iostream>
namespace qi = boost::spirit::qi;
int main(int, char**) {
auto txt = +(qi::char_("a-zA-Z_"));
auto rule = qi::lit("Hello") >> txt % ',' >> "end";
std::string str = "HelloFoo,Moo,Bazend";
std::string::iterator begin = str.begin();
if (qi::parse(begin, str.end(), rule))
std::cout << "Match !" << std::endl;
else
std::cout << "No match :'(" << std::endl;
}

最佳答案

这是我的版本,更改标记为:

#include <boost/spirit/include/qi.hpp>
#include <iostream>
namespace qi = boost::spirit::qi;
int main(int, char**) {
auto txt = qi::lexeme[+(qi::char_("a-zA-Z_"))]; // CHANGE: avoid eating spaces
auto rule = qi::lit("Hello") >> txt % ',' >> "end";
std::string str = "Hello Foo, Moo, Baz end"; // CHANGE: re-introduce spaces
std::string::iterator begin = str.begin();
if (qi::phrase_parse(begin, str.end(), rule, qi::ascii::space)) { // CHANGE: used phrase_parser with a skipper
std::cout << "Match !" << std::endl << "Remainder (should be empty): '"; // CHANGE: show if we parsed the whole string and not just a prefix
std::copy(begin, str.end(), std::ostream_iterator<char>(std::cout));
std::cout << "'" << std::endl;
}
else {
std::cout << "No match :'(" << std::endl;
}
}

这可以用 GCC 4.4.3 和 Boost 1.4something 编译和运行;输出:

Match !
Remainder (should be empty): ''

通过使用 lexeme,您可以避免有条件地吃掉空格,这样 txt 只匹配一个单词边界。这会产生预期的结果:因为 "Baz" 后面没有逗号,而且 txt 不占用空格,所以我们不会意外地使用 "end".

无论如何,我不能 100% 确定这就是您要查找的内容——特别是 str 是否缺少空格作为说明性示例,或者您是否以某种方式被迫使用此 (无空格)格式?

旁注:如果您想确保已解析整个字符串,请添加一个检查以查看是否 begin == str.end()。如前所述,即使仅解析了 str 的非空前缀,您的代码也会报告匹配项。

更新 添加后缀打印。

关于c++ - Boost精神太贪心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5355715/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com