这是我的快速实现( c++11 )。你可以找到很多场景如何解决boost-spirit-qi中的各种问题,我同意学习 SPIRIT 需要一些努力:-)
#define BOOST_RESULT_OF_USE_DECLTYPE
#define BOOST_SPIRIT_USE_PHOENIX_V3
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
struct SInsert
{
struct result
{
typedef void type;
};
void operator()( std::vector<std::string>&out,
std::vector<std::string>&in, int counter ) const
{
for( int i=0; i<counter; ++i )
std::copy( in.begin(), in.end(), std::back_inserter(out) );
}
};
boost::phoenix::function<SInsert> inserter;
int main()
{
namespace qi = boost::spirit::qi;
namespace ph = boost::phoenix;
namespace ascii = boost::spirit::ascii;
for ( auto &str : std::vector< std::string >
{ "w1/ w2 /w4 ",
"[w2]1 /w4 ",
"[w2/w3]2 /w4 ",
"[]0",
"[]0 / w4"
}
)
{
std::cout << "input:" << str << std::endl;
std::string::const_iterator iter( str.begin() );
std::string::const_iterator last( str.end() );
std::vector< std::string > v;
qi::rule<std::string::const_iterator,
qi::locals< std::vector<std::string> >,
ascii::space_type ,std::vector<std::string>()> mrule =
( qi::as_string[ qi::lexeme[ +(qi::graph -"/"-"[") ] ][ ph::push_back( qi::_val,qi::_1 )] |
(
qi::lit("[")
>> -(
qi::eps[ ph::clear( qi::_a ) ]
>> qi::as_string[ qi::lexeme[ +(qi::graph-"/"-"]") ] ][ ph::push_back( qi::_a ,qi::_1 ) ]
% qi::lit("/")
)
)
>> qi::lit("]" )
>> qi::int_[ inserter( qi::_val,qi::_a,qi::_1 ) ]
)
% qi::lit("/");
if( qi::phrase_parse( iter, last, mrule , ascii::space, v ) && iter==last )
std::copy( v.begin(), v.end(),
std::ostream_iterator<std::string>( std::cout,"\n" ));
else
std::cerr << "parsing failed:" << *iter << std::endl;
}
return 0;
}
您可以进一步简化,mrule
以便自动合成属性而不是使用语义操作 - 即使您不会完全避免它们:
qi::rule<std::string::const_iterator,
qi::locals< std::vector<std::string> >,
ascii::space_type ,std::vector<std::string>()> mrule;
mrule %=
(
qi::as_string[ qi::lexeme[ +(qi::graph -"/"-"[") ] ] |
qi::lit("[")
>> -(
qi::eps[ ph::clear( qi::_a ) ]
>> qi::as_string[ qi::lexeme[ +(qi::graph-"/"-"]") ] ][ ph::push_back( qi::_a ,qi::_1 ) ]
% qi::lit("/")
)
>> qi::lit("]" )
>> qi::omit[ qi::int_[ inserter( qi::_val,qi::_a,qi::_1-1 ) ] ]
)
% qi::lit("/");
正如所sehe
指出的一些丑陋的结构,这里是一个小的简化:
qi::rule<std::string::const_iterator,
qi::locals< std::vector<std::string> >,
ascii::space_type ,std::vector<std::string>()> mrule;
mrule %= (
qi::as_string[ qi::lexeme[ +qi::alnum ] ] |
qi::lit("[")
>> -(
qi::eps[ ph::clear( qi::_a ) ] >>
qi::as_string[ qi::lexeme[ +qi::alnum ] ][ ph::push_back( qi::_a ,qi::_1 ) ]
% qi::lit("/")
)
>> qi::lit("]")
>> qi::omit[ qi::int_[ inserter( qi::_val,qi::_a,qi::_1-1 ) ] ]
) % qi::lit("/");