2010-05-17 84 views

回答

2

這是我到目前爲止已經發現:

text = "alpha beta"; 
string::const_iterator begin = text.begin(); 
string::const_iterator end = text.end(); 
boost::match_results<string::const_iterator> what; 
while (regex_search(begin, end, what, boost::regex("([a-z]+)"))) { 
    cout << string(what[1].first, what[2].second-1); 
    begin = what[0].second; 
} 

而且它按預期工作。也許有人知道更好的解決方案?

2

你不應該驗證什麼東西匹配之前調用matches.size(),即你的代碼應該看起來有點像這樣:

#include <boost/regex.hpp> 
boost::cmatch matches; 
if (boost::regex_match("alpha beta", matches, boost::regex("([a-z])+"))) 
    cout << "found: " << matches.size() << endl; 
else 
    cout << "nothing found" << endl; 

輸出將是「沒有發現」,因爲regex_match嘗試匹配整個字符串。你想要的可能是正在尋找子串的regex_search。下面的代碼可能是你一個好一點:

#include <boost/regex.hpp> 
boost::cmatch matches; 
if (boost::regex_search("alpha beta", matches, boost::regex("([a-z])+"))) 
    cout << "found: " << matches.size() << endl; 
else 
    cout << "nothing found" << endl; 

但會輸出唯一的「2」,即[0]與「阿爾法」和火柴[1]與「一」(最後一個字母的字母相匹配 - 最後一組匹配)

要獲取組中的整個單詞,您必須將模式更改爲([az] +),並重復調用regex_search,就像您在自己的答案中一樣。

抱歉發表迴應2旬,但如果有人在這裏網上搜尋像我一樣,那麼也許這將是對還是他有用...

0

這個工作對我來說,也許有人會發現它有用..

std::string arg = "alpha beta"; 
boost::sregex_iterator it{arg.begin(), arg.end(), boost::regex("([a-z])+")}; 
boost::sregex_iterator end; 
for (; it != end; ++it) { 
    std::cout << *it << std::endl; 
} 

打印:

alpha 
beta 
相關問題