2013-05-21 41 views
1

我有和字符串"SolutionAN ANANANA SolutionBN"我想返回所有以Solution開頭並以N結尾的字符串。Boost C++正則表達式 - 如何返回所有匹配項

雖然使用正則表達式boost::regex regex("Solu(.*)N"); 我得到的輸出爲SolutionAN ANANANA SolutionBN

雖然我想出去作爲SolutionANSolutionBN。我是新的正則表達式提升任何幫助將不勝感激。 片段,如果代碼我使用

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

int main(int ac,char* av[]) 
{ 
    std::string strTotal("SolutionAN ANANANA SolutionBN"); 
    boost::regex regex("Solu(.*)N"); 

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

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

回答

1

的問題是,*是貪婪的。更改爲使用非貪婪版本(注意?):

int main(int ac,char* av[]) 
{ 
    std::string strTotal("SolutionAN ANANANA SolutionBN"); 
    boost::regex regex("Solu(.*?)N"); 

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

    for(; iter != end; ++iter) { 
      std::cout<<*iter<<std::endl; 
    } 
} 
+0

謝謝你,我有一個正則表達式的其他疑問,假設我有輸入SolutionAN ANANANA SolutionBN ABC美國廣播公司的解決方案。我想與SOLU和月底開始的所有字符串中的下一個SOLU上手例如 輸入:SolutionAN ANANANA SolutionBN ABC美國廣播公司的解決方案 輸出:3不同的字符串 SolutionAN ANANANA SolutionBN ABC ABC 解決方案 –

相關問題