2015-04-12 24 views
1

我是新來推動,並試圖構建一個載體,(這將是(Y /否)&次數保存方向的物體的向量)從以下字符串中的字段,但此字符串長度會是任意的,可以有人建議我該如何確切的字符串boost::regex &店與之相匹配?遞歸配以升壓regex庫

std::string str = "Y-10,NO-3,NO-4,Y-100" 

編輯: 這是我做了什麼,但不知道這是否是最佳的?

boost::regex expr{"((Y|NO)-\\d+)"}; 
boost::regex_token_iterator<std::string::iterator> it{pattern.begin(), pattern.end(), expr, 1}; 
boost::regex_token_iterator<std::string::iterator> end; 
while (it != end) { 
    std::string pat = *it; 
    boost::regex sub_expr {"(Y|NO)-(\\d+)"}; 
    boost::smatch match; 
    if (boost::regex_search(pat, match, sub_expr)) { 
     ... 
     ...  
    } 
} 

回答

1

我在這裏使用精神:

Live On Coliru

#include <boost/fusion/adapted/std_pair.hpp> 
#include <boost/spirit/include/qi.hpp> 
namespace qi = boost::spirit::qi; 

enum class YNO { NO, Y }; 

struct YNoToken : qi::symbols<char, YNO> { 
    YNoToken() { add("Y", YNO::Y)("NO", YNO::NO); } 
} static YNo; 

int main() { 
    std::string const str = "Y-10,NO-3,NO-4,Y-100"; 
    auto f = str.begin(), l = str.end(); 

    std::vector<std::pair<YNO, int> > v; 

    bool ok = qi::parse(f, l, (YNo >> '-' >> qi::int_) % ',', v); 
    if (ok) { 
     std::cout << "Parse success: \n"; 
     for (auto pair : v) 
      std::cout << (pair.first==YNO::Y? "Y":"NO") << "\t" << pair.second << "\n"; 
    } 
    else 
     std::cout << "Parse failed\n"; 

    if (f!=l) 
     std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n"; 
} 

打印

Parse success: 
Y 10 
NO 3 
NO 4 
Y 100 

可以實現與正則表達式類似的結果,但你」 d離開做檢查和轉換子匹配手動工作。

+0

感謝您的建議,我喜歡這種方法,雖然之前沒有使用這些庫 – Jim