c++boost-spirit

boost::spirit reusage of grammar objects


Imagine there is a rule to parse some name:

m_sName = qi::lexeme[
    (ascii::alpha | qi::char_('_')) >> *(ascii::alnum | qi::char_('_'))
]

Could one use the same object for parsing two names in series or does one have to instantiate m_sName1 and m_sName2?

m_sName >> m_sName

Solution

  • I made a sample that might help:

    Live On Coliru

    #include <boost/spirit/include/qi.hpp>
    #include <iomanip>
    
    int main() {
        namespace qi = boost::spirit::qi;
        using It     = std::string::const_iterator;
    
        qi::rule<It, std::string()> m_sName = (qi::alpha | qi::char_('_')) >> *(qi::alnum | qi::char_('_'));
    
        for (std::string const input : {"foo bar qux_net"}) {
            std::string a, b, c;
            if (phrase_parse(input.begin(), input.end(), m_sName >> m_sName >> m_sName, qi::space, a, b, c)) {
                std::cout << quoted(a) << " " << quoted(b) << " " << quoted(c) << "\n";
            }
        }
    }
    

    Prints

    "foo" "bar" "qux_net"
    

    NOTES