c – 使用boost spirit从括号中提取字符串

我有以下字符串:

%%DocumentNeededResources: CMap (90pv-RKSJ-UCS2C)

我想解析它并存储/提取括号中的90pv-RKSJ-UCS2C字符串.

我的规则如下:

std::string strLinesRecur = "%%DocumentNeededResources: CMap (90pv-RKSJ-UCS2C)";
std::string strStartTokenRecur;
std::string token_intRecur;
bool bParsedLine1 = qi::phrase_parse(strLinesRecur.begin(), strLinesRecur.end(), +char_>>+char_,':', token_intRecur, strStartTokenRecur);

最佳答案 看起来你认为船长是拆分分隔符.这恰恰相反(
Boost spirit skipper issues).

在这种罕见的情况下,我想我更喜欢正则表达式.但是,既然你问这里的精神:

Live On Coliru

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

namespace qi = boost::spirit::qi;

int main() {
    std::string const line = "%%DocumentNeededResources: CMap (90pv-RKSJ-UCS2C)";

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

    std::string label, token;
    bool ok = qi::phrase_parse(
            first, last, 
            qi::lexeme [ "%%" >> +~qi::char_(":") ] >> ':' >> qi::lexeme["CMap"] >> '(' >> 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";
}

打印

Parse success: label='DocumentNeededResources', token='90pv-RKSJ-UCS2C'
点赞