c – 使用精神解析器从字符串中提取值

我有以下行

/ 90pv-RKSJ-UCS2C usecmap

std::string const line = "/90pv-RKSJ-UCS2C usecmap";

auto first = line.begin(), last = line.end();

std::string label, token;
bool ok = qi::phrase_parse(
        first, last, 
        qi::lexeme [ "/" >> +~qi::char_(" ") ] >> ' ' >>  qi::lexeme[+~qi::char_(' ')] , qi::space, label, token);


if (ok)
    std::cout << "Parse success: label='" << label << "', token='" << token << "'\n";
else
    std::cout << "Parse failed\n";

if (first!=last)
    std::cout << "Remaining unparsed input: '" << std::string(first, last) << "'\n";

我想在标签中使用90pv-RKSJ-UCS2C并在令牌变量中使用usecmap.

我提取90pv-RKSJ-UCS2C值但不提取usecmap

最佳答案 随着船长的空间,你不能匹配”(它被跳过!).另见:
Boost spirit skipper issues

所以,要么不使用船长,要么让船长吃掉它:

bool ok = qi::phrase_parse(
        first, last, 
        qi::lexeme [ "/" >> +qi::graph ] >> qi::lexeme[+qi::graph], qi::blank, label, token);

笔记:

>我使用qi :: graph而不是~qi :: char_(“”)公式
>因为你说过,我使用了blank_type

i have following line

这意味着不应该跳过行尾

演示

Live On Coliru

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

namespace qi = boost::spirit::qi;

int main()
{
    std::string const line = "/90pv-rksj-ucs2c usecmap";

    auto first = line.begin(), last = line.end();

    std::string label, token;
    bool ok = qi::phrase_parse(
            first, last, 
            qi::lexeme [ "/" >> +qi::graph ] >> qi::lexeme[+qi::graph], qi::blank, label, token);

    if (ok)
        std::cout << "parse success: label='" << label << "', token='" << token << "'\n";
    else
        std::cout << "parse failed\n";

    if (first!=last)
        std::cout << "remaining unparsed input: '" << std::string(first, last) << "'\n";
}

打印:

parse success: label='90pv-rksj-ucs2c', token='usecmap'
点赞