2010-06-26 44 views
13

如果我有一個簡單的正則表達式模式,如「ab」。我有一個字符串有多個匹配像「abc abd」。如果我做了以下...Boost C++正則表達式 - 如何獲取多個匹配

boost::match_flag_type flags = boost::match_default; 
boost::cmatch mcMatch; 
boost::regex_search("abc abd", mcMatch, "ab.", flags) 

然後mcMatch包含第一個「abc」結果。我怎樣才能獲得所有可能的比賽?

回答

25

可以使用boost::sregex_token_iterator就像這個小例子:

#include <boost/regex.hpp> 
#include <iostream> 
#include <string> 

int main() { 
    std::string text("abc abd"); 
    boost::regex regex("ab."); 

    boost::sregex_token_iterator iter(text.begin(), text.end(), regex, 0); 
    boost::sregex_token_iterator end; 

    for(; iter != end; ++iter) { 
     std::cout<<*iter<<'\n'; 
    } 

    return 0; 
} 

從這個程序的輸出是:

abc 
abd 
+0

感謝您的快速回復。問題,* iter返回的是什麼,它在我的快速測試中似乎不是boost :: cmatch?我只是舉了一個非常簡單的例子。在我的正則表達式中,我可能有組,所以我需要訪問每場比賽的組信息(可從cmatch獲得)? – Ron 2010-06-26 02:06:20

+0

您可以嘗試使用regex_iterator,它會在解除引用時返回match_result,並且應該爲您提供所需的內容? – Jacob 2010-06-26 08:32:58