2013-02-21 57 views
5

我試圖使用升壓精神框架來定義我自己的語法,我定義這樣的匹配規則:升壓精神得到了全場比賽作爲字符串

value = (
     char_('"') >> 
     (*qi::lexeme[ 
       char_('\\') >> char_('\\') | 
       char_('\\') >> char_('"') | 
       graph - char_('"') | 
       char_(' ') 
     ])[some_func] >> 
     char_('"') 
); 

我想assing動作 - some_func - 到它的一部分,並傳遞整個匹配字符串作爲參數。但不幸的是我會得到像vector<boost::variant<boost::fusion::vector2 ..a lot of stuff...)...>。我可以以某種方式獲取整個數據作爲char *,std :: string甚至void *的大小?

+0

什麼是錯的矢量? – 2013-02-21 01:27:14

+0

我將它描述爲一個向量 >>>但它是由sehe編輯的。 – Dejwi 2013-02-21 16:18:03

回答

8

qi::as_string

演示程序的輸出:

DEBUG: 'some\\"quoted\\"string.' 
parse success 

說實話,它看起來像你確實試圖解析與可能的逃逸字符「逐字」字符串。在這方面,使用lexeme似乎是錯誤的(空間被吃掉)。如果您想查看轉義字符串解析的樣本,請參閱

一個簡單的重排,我認爲可以做,至少可能看起來像:

0然而

需要注意的是,你可以簡單地聲明該規則沒有船長和刪除lexeme總數:http://liveworkspace.org/code/1oEhei$0

代碼(住在liveworkspace

#include <boost/fusion/adapted.hpp> 
#include <boost/spirit/include/qi.hpp> 
#include <boost/spirit/include/phoenix.hpp> 

namespace qi = boost::spirit::qi; 
namespace phx = boost::phoenix; 

struct some_func_t 
{ 
    template <typename> struct result { typedef void type; }; 
    template <typename T> 
     void operator()(T const& s) const 
     { 
      std::cout << "DEBUG: '" << s << "'\n"; 
     } 
}; 

template <typename It, typename Skipper = qi::space_type> 
    struct parser : qi::grammar<It, Skipper> 
{ 
    parser() : parser::base_type(value) 
    { 
     using namespace qi; 
     // using phx::bind; using phx::ref; using phx::val; 

     value = (
       char_('"') >> 
        qi::as_string 
        [ 
         (*qi::lexeme[ 
          char_('\\') >> char_('\\') | 
          char_('\\') >> char_('"') | 
          graph - char_('"') | 
          char_(' ') 
          ]) 
        ] [some_func(_1)] >> 
       char_('"') 
      ); 
     BOOST_SPIRIT_DEBUG_NODE(value); 
    } 

    private: 
    qi::rule<It, Skipper> value; 
    phx::function<some_func_t> some_func; 
}; 

bool doParse(const std::string& input) 
{ 
    typedef std::string::const_iterator It; 
    auto f(begin(input)), l(end(input)); 

    parser<It, qi::space_type> p; 

    try 
    { 
     bool ok = qi::phrase_parse(f,l,p,qi::space); 
     if (ok) 
     { 
      std::cout << "parse success\n"; 
     } 
     else  std::cerr << "parse failed: '" << std::string(f,l) << "'\n"; 

     if (f!=l) std::cerr << "trailing unparsed: '" << std::string(f,l) << "'\n"; 
     return ok; 
    } catch(const qi::expectation_failure<It>& e) 
    { 
     std::string frag(e.first, e.last); 
     std::cerr << e.what() << "'" << frag << "'\n"; 
    } 

    return false; 
} 

int main() 
{ 
    bool ok = doParse("\"some \\\"quoted\\\" string.\""); 
    return ok? 0 : 255; 
} 
+1

+1我早些時候會用'as_string'來回答,但是我不能在文檔中找到它 - 「解析器指令」,呃! – ildjarn 2013-02-21 01:36:35

+0

新增了一個具體說明,我認爲_needs_在使用'lexeme'時會被固定。 – sehe 2013-02-21 08:11:27