
Matthew Peltzer wrote:
I am trying to use Spirit to parse lines like:
name:value
but, name might contain colons also. I've not been able to come up with anything that parses this correctly without swallowing up the rest of the document. Anyone able to help?
Seeing your code would be a good first step in helping you, but I imagine something like the following should work as desired:
+(+(alnum_p | ':') >> ':' >> +(alnum_p) >> eol_p);
I do not think that will work because plus, like the kleene, is greedy. The second ':' will not ever see the light of day. Try right recursion: name = alnum_p | ':'; name_colon = name >> (name_colon | ':'); start = name_colon >> value; When you do not want greedy iteration (kleene, plus), right recursion is your friend. The rule name_colon is guaranteed to end with a colon and name may have colons. Try attached code. BTW, please post to Spirit's mailing list. It's the proper forum for Spirit related questions: Spirit-general mailing list Spirit-general@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/spirit-general HTH, -- Joel de Guzman http://www.boost-consulting.com http://spirit.sf.net /*============================================================================= Copyright (c) 2002-2003 Joel de Guzman http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #include <boost/spirit/core.hpp> #include <iostream> #include <string> /////////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; /////////////////////////////////////////////////////////////////////////////// // // My grammar // /////////////////////////////////////////////////////////////////////////////// struct my_grammar : public grammar<my_grammar> { template <typename ScannerT> struct definition { definition(my_grammar const& self) { value = int_p; name = alnum_p | ':'; name_colon = name >> (name_colon | ':'); start_ = name_colon >> value; } rule<ScannerT> start_, name, name_colon, value; rule<ScannerT> const& start() const { return start_ ; } }; }; /////////////////////////////////////////////////////////////////////////////// // // Main program // /////////////////////////////////////////////////////////////////////////////// int main() { cout << "/////////////////////////////////////////////////////////\n\n"; cout << "\t\t A right recursion example...\n\n"; cout << "/////////////////////////////////////////////////////////\n\n"; cout << "Type anything or [q or Q] to quit\n\n"; my_grammar g; string str; while (getline(cin, str)) { if (str[0] == 'q' || str[0] == 'Q') break; if (parse(str.c_str(), g, space_p).full) { cout << "parsing succeeded\n"; } else { cout << "parsing failed\n"; } } cout << "Bye... :-) \n\n"; return 0; }