2011-03-18 38 views
8

我在大約一個升壓深深折服之間是::精神和永恆的挫折並不理解它;)升壓精神過於貪婪

我有一個字符串過於貪婪的問題,因此它不匹配。下面是一個最小的例子,它不會隨着txt規則的結束而解析。

有關我想要做什麼的更多信息:目標是解析一些僞SQL,並跳過空格。在像

select foo.id, bar.id from foo, baz 

聲明我需要把from作爲一個特殊的關鍵字。規則是類似於

"select" >> txt % ',' >> "from" >> txt % ',' 

但它顯然不工作,它看到bar.id from foo作爲一個項目。

#include <boost/spirit/include/qi.hpp> 
#include <iostream> 
namespace qi = boost::spirit::qi; 
int main(int, char**) { 
    auto txt = +(qi::char_("a-zA-Z_")); 
    auto rule = qi::lit("Hello") >> txt % ',' >> "end"; 
    std::string str = "HelloFoo,Moo,Bazend"; 
    std::string::iterator begin = str.begin(); 
    if (qi::parse(begin, str.end(), rule)) 
     std::cout << "Match !" << std::endl; 
    else 
     std::cout << "No match :'(" << std::endl; 
} 

回答

10

這裏是我的版本,有明顯的變化:

#include <boost/spirit/include/qi.hpp> 
#include <iostream> 
namespace qi = boost::spirit::qi; 
int main(int, char**) { 
    auto txt = qi::lexeme[+(qi::char_("a-zA-Z_"))];  // CHANGE: avoid eating spaces 
    auto rule = qi::lit("Hello") >> txt % ',' >> "end"; 
    std::string str = "Hello Foo, Moo, Baz end";  // CHANGE: re-introduce spaces 
    std::string::iterator begin = str.begin(); 
    if (qi::phrase_parse(begin, str.end(), rule, qi::ascii::space)) {   // CHANGE: used phrase_parser with a skipper 
    std::cout << "Match !" << std::endl << "Remainder (should be empty): '"; // CHANGE: show if we parsed the whole string and not just a prefix 
    std::copy(begin, str.end(), std::ostream_iterator<char>(std::cout)); 
    std::cout << "'" << std::endl; 
    } 
    else { 
    std::cout << "No match :'(" << std::endl; 
    } 
} 

這編譯並與GCC 4.4.3運行和Boost 1.4something;輸出:

Match ! 
Remainder (should be empty): '' 

使用lexeme,就可以避免吃有條件的空間,讓txt比賽最多也只有一個字邊界。這產生了期望的結果:因爲"Baz"後面沒有逗號,並且txt不吃空格,所以我們從不意外地消耗"end"

無論如何,我不是100%確定這是你正在尋找的 - 特別是,str缺少空格作爲一個說明性的例子,或者你在某種程度上被迫使用這種(無空格)格式?

注意:如果你想確保你已經解析了整個字符串,請添加一個檢查以查看是否begin == str.end()。如上所述,即使只解析了非空前綴str,您的代碼也會報告匹配。

更新:添加後綴打印。

+0

謝謝!這個詞語是我錯過的東西。你完全正確地添加空格(我在示例中將它們留在了最小的東西上,但我想它比任何東西都更令人困惑) – 2011-03-20 09:20:23

+0

幸運的猜測;)謝謝。 – phooji 2011-03-21 01:42:34