是否可以使用boost :: spirit :: qi来解析以下内容?
A_B --> (A, B)
A_B_C --> (A_B, C)
A_B_C_D --> (A_B_C, D)
A_B_C_D_E --> (A_B_C_D, E)
我想生成规则,以便我可以匹配字符串中的最后一个'_'并在其上拆分字符串。
答案 0 :(得分:3)
这看起来像一个奇怪的语法,对于一个专门的函数来说是一个更好的工作(特别是因为你的样本中的源“令牌”实际上非常短)。
然而,不用多说,这就是你可以用Spirit做的事情:
name = lexeme [ +(graph - '_') ]; // or just char_("ABCDEFG") if it's that simple
entry = lexeme [ raw [ +(name >> '_') ] >> name ];
再次,请参阅http://liveworkspace.org/code/15d970571a61dd39faedc8b7231ef67d
上的代码// #define BOOST_SPIRIT_DEBUG
#include <boost/fusion/adapted.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <map>
namespace qi = boost::spirit::qi;
namespace karma = boost::spirit::karma;
namespace phx = boost::phoenix;
typedef std::map<std::string, std::string> pairs_t;
template <typename It, typename Skipper = qi::space_type>
struct parser : qi::grammar<It, pairs_t(), Skipper>
{
parser() : parser::base_type(start)
{
using namespace qi;
name = lexeme [ +(graph - '_') ]; // or just char_("ABCDEFG") if it's that simple
entry = lexeme [ raw [ +(name >> '_') ] >> name ];
start = *entry;
BOOST_SPIRIT_DEBUG_NODE(name);
BOOST_SPIRIT_DEBUG_NODE(entry);
BOOST_SPIRIT_DEBUG_NODE(start);
}
private:
qi::rule<It, std::string()> name;
qi::rule<It, std::pair<std::string, std::string>(), Skipper> entry;
qi::rule<It, pairs_t(), Skipper> start;
};
template <typename C, typename Skipper>
bool doParse(const C& input, const Skipper& skipper)
{
auto f(std::begin(input)), l(std::end(input));
parser<decltype(f), Skipper> p;
pairs_t data;
try
{
bool ok = qi::phrase_parse(f,l,p,skipper,data);
if (ok)
{
std::cout << "parse success\n";
std::cout << "data: " << karma::format_delimited(karma::auto_ % ';', ' ', data) << '\n';
}
else std::cerr << "parse failed: '" << std::string(f,l) << "'\n";
if (f!=l) std::cerr << "trailing unparsed: '" << std::string(f,l) << "'\n";
return ok;
} catch(const qi::expectation_failure<decltype(f)>& e)
{
std::string frag(e.first, e.last);
std::cerr << e.what() << "'" << frag << "'\n";
}
return false;
}
int main()
{
const std::string input = "A_B A_B_C A_B_C_D A_B_C_D_E";
bool ok = doParse(input, qi::blank);
return ok? 0 : 255;
}