Search code examples
c++boostboost-spiritboost-spirit-qi

extracting string from bracket using boost spirit


I have the following string:

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

I want to parse it and store/extract the 90pv-RKSJ-UCS2C string which is in bracket.

My rule is as follows:

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);

Solution

  • It looks like you thought a skipper is a split delimiter. It's quite the opposite (Boost spirit skipper issues).

    In this rare circumstance I think I'd prefer a regular expression. But, since you asked here's the spirit take:

    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";
    }
    

    Prints

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