Fra*_*ank 7 c++ parsing boost boost-spirit boost-spirit-qi
我正在努力学习boost::spirit.作为一个例子,我试图将一系列单词解析成一个单词vector<string>.我试过这个:
#include <boost/spirit/include/qi.hpp>
#include <boost/foreach.hpp>
namespace qi = boost::spirit::qi;
int main() {
std::vector<std::string> words;
std::string input = "this is a test";
bool result = qi::phrase_parse(
input.begin(), input.end(),
+(+qi::char_),
qi::space,
words);
BOOST_FOREACH(std::string str, words) {
std::cout << "'" << str << "'" << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
这给了我这个输出:
'thisisatest'
Run Code Online (Sandbox Code Playgroud)
但我想要以下输出,其中每个单词分别匹配:
'this'
'is'
'a'
'test'
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我想避免qi::grammar为这个简单的情况定义我自己的子类.
ild*_*arn 14
你从根本上误解了(或者至少是误用)跳过解析器的目的 - qi::space用作跳过解析器,用于使你的解析器空白不可知,这样a b和之间没有区别ab.
在您的情况下,空格很重要,因为您希望它分隔单词.因此,您不应该跳过空格,qi::parse而是想要使用而不是qi::phrase_parse:
#include <vector>
#include <string>
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/spirit/include/qi.hpp>
int main()
{
namespace qi = boost::spirit::qi;
std::string const input = "this is a test";
std::vector<std::string> words;
bool const result = qi::parse(
input.begin(), input.end(),
+qi::alnum % +qi::space,
words
);
BOOST_FOREACH(std::string const& str, words)
{
std::cout << '\'' << str << "'\n";
}
}
Run Code Online (Sandbox Code Playgroud)
(现在更新了G. Civardi的修复.)