如何在Boost.Sprit.Qi中使用vector <string>组合ascii :: string规则?

时间:2018-02-15 06:36:13

标签: c++ boost boost-spirit-qi

我想从字符串中搜索特定的字符位置。 特定字符由向量给出。 所以,我想结合来自vector的ascii :: string规则。

我用&#34; | =&#34;操作数。但它不起作用。

#include <iostream>
#include <string>
#include <vector>

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>

namespace qi    = boost::spirit::qi;
namespace ascii    = boost::spirit::ascii;

int main()
{
    std::string test = "abc def aaa ffew";
    auto itr = test.begin(), end = test.end();

    std::vector<std::string> find_list = {"des", "ffe", "asaa"};
    std::string result;

    {
        std::string result;
        qi::rule<std::string::iterator, std::string()> rule;
        rule = ascii::string(find_list[0]) | ascii::string(find_list[1]) | ascii::string(find_list[2]);
        // this works
        if (qi::parse(itr, end, (qi::omit[*(qi::char_ - rule)] >> rule), result)) {
            std::cout << result << std::endl;
        } else std::cout << "failed." << std::endl;
    }

    itr = test.begin();

    // Sample that what I want to do
    {
        std::string result;
        qi::rule<std::string::iterator, std::string()> rule;
        for (auto && str : find_list) {
            // this is not equals rule = ascii::string(find_list)[0] | ascii::string(find_list)[1] | .... [n] ??
            rule |= ascii::string(str); 
        }
        // this not works
        if (qi::parse(itr, end, (qi::omit[*(qi::char_ - rule)] >> rule), result)) {
            std::cout << result << std::endl;
        } else std::cout << "failed." << std::endl;

    }

    return 0;
}

输出:

ffe
failed.
0

我该怎么办? 感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

不要重新发明轮子。 Spirit已经为此提供了一个高度优化的解析器:qi::symbols<>

<强> Live On Coliru

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/repository/include/qi_seek.hpp>

namespace qi = boost::spirit::qi;
namespace qr = boost::spirit::repository::qi;

int main() {
    std::string const test = "abc def aaa ffew";

    qi::symbols<char> find_list;
    find_list += "des", "ffe", "asaa";

    std::string result;
    if (qi::parse(test.begin(), test.end(), qr::seek[qi::raw[find_list]], result)) {
        std::cout << result << std::endl;
    } else {
        std::cout << "failed." << std::endl;
    }
}

打印

ffe
来自Spirit Repository的

没有seek[] 它变得更短但效率更低: 的 Live On Coliru