然而若是搜索字符串中有多個匹配結果,則須要本身實現了。ios
在smatch中,有兩個成員,官方文檔以下:express
iterator first:函數
An iterator denoting the position of the start of the match.spa
iterator second.net
An iterator denoting the position of the end of the match.code
因此,使用以下方法,能夠獲得遍歷搜索:blog
- #include <string>
- #include <iostream>
- #include <boost\regex.hpp>
- int main()
- {
- std::string str = "192.168.1.1";
-
- boost::regex expression("\\d+");
- boost::smatch what;
-
- std::string::const_iterator start = str.begin();
- std::string::const_iterator end = str.end();
- while ( boost::regex_search(start, end, what, expression) )
- {
- std::cout << what[0] << std::endl;
- start = what[0].second;
- }
- return 0;
- }
結果以下:
在boost中,還提供了一種迭代器的方法,名稱爲:sregex_iterator,默認構造器會生成一個結束迭代器。用法以下:ip
- #include <string>
- #include <iostream>
- #include <boost\regex.hpp>
- int main()
- {
- std::string str = "192.168.1.1";
-
- boost::regex expression("\\d+");
- boost::sregex_iterator it(str.begin(), str.end(), expression);
- boost::sregex_iterator end;
- for (; it != end; ++it)
- std::cout << *it << std::endl;
-
- return 0;
- }
效果與上一例相同。
boost::cmatch mat; boost::regex reg( "\\d+" ); //查找字符串裏的數字 if(boost::regex_search(szStr, mat, reg)) { cout << "searched:" << mat[0] << endl; } }