使用Boost Regex 的regex_search進行遍歷搜索


在regex_search函數中,會將找到的第一個匹配結果保存到一個smatch類中。

然而如果搜索字符串中有多個匹配結果,則需要自己實現了。

在smatch中,有兩個成員,官方文檔如下:

iterator first:

An iterator denoting the position of the start of the match.

iterator second

An iterator denoting the position of the end of the match.

所以,使用如下方法,可以得到遍歷搜索:

 

[cpp]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. #include <string>  
  2. #include <iostream>  
  3. #include <boost\regex.hpp>  
  4. int main()  
  5. {  
  6.     std::string str = "192.168.1.1";  
  7.   
  8.     boost::regex expression("\\d+");  
  9.     boost::smatch what;  
  10.   
  11.     std::string::const_iterator start = str.begin();  
  12.     std::string::const_iterator end = str.end();  
  13.     while ( boost::regex_search(start, end, what, expression) )  
  14.     {  
  15.         std::cout << what[0] << std::endl;  
  16.         start = what[0].second;  
  17.     }  
  18.     return 0;  
  19. }  

結果如下:

 

 

[plain]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. 192  
  2. 168  
  3. 1  
  4. 1  

在boost中,還提供了一種迭代器的方法,名稱為:sregex_iterator,默認構造器會生成一個結束迭代器。用法如下:

 

[cpp]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. #include <string>  
  2. #include <iostream>  
  3. #include <boost\regex.hpp>  
  4. int main()  
  5. {  
  6.     std::string str = "192.168.1.1";  
  7.   
  8.     boost::regex expression("\\d+");  
  9.     boost::sregex_iterator it(str.begin(), str.end(), expression);  
  10.     boost::sregex_iterator end;  
  11.     for (; it != end; ++it)  
  12.         std::cout << *it << std::endl;  
  13.   
  14.     return 0;  
  15. }  

效果與上一例相同。
 
如果不需要遍歷,只需要匹配,那更簡單:
    boost::regex reg( szReg );
    bool r=boost::regex_match( szStr , reg);
或是需要放入一個cmatch 中:
{
    boost::cmatch mat;
    boost::regex reg( "\\d+" );    //查找字符串里的數字
    if(boost::regex_search(szStr, mat, reg))
    {
        cout << "searched:" << mat[0] << endl;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM