在实际的应用中,经常用到boost:regex进行字符串的分割,特别是windows下的路径字符串的分割,由于windows的路径字符串带有特殊字符'\',boost:regex需要对此进行特殊处理,下面举例说明,分割字符串的正则表达式如下:
boost::regex reg("\\\\");
由于反斜杠对于c++字符和regex来说都是特殊字符,因而需要转义两次,才能正确执行。
完整代码如下:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <boost/regex.hpp>using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<std::string> vec;
std::string s = "F:\\OtherProjects\\BasePlatForm\\C21\\SMC\\Backend\\Src";
try
{
boost::regex reg("\\\\");
boost::sregex_token_iterator it(s.begin(),s.end(),reg,-1);
boost::sregex_token_iterator end;while(it != end)
{
vec.push_back(*it++);
}}
catch(boost::regex_error &err)
{
cout<<err.what()<<endl;
cin.get();
return 0;
}
catch(...)
{
cout<<"error"<<endl;
cin.get();
return 0;
}
assert(vec.size() == std::count(s.begin(),s.end(),'//')+1);for(int i =0;i<vec.size();i++)
{
cout<<vec[i]<<endl;
}cin.get();
return 0;
}希望本文能给有同样问题的人,有点帮助~~~