参考之前写的:http://blog.sina.com.cn/s/blog_48d4cf2d0100r9hv.html。主要是增加一个regexEscape函数,免得只想使用字符串而不是正则表达式时数反斜杠数得眼花。有写几个测试用例,应该没啥大问题。
=======================代码的分割线================================
#include <string>
#include <vector>
#include <boost/regex.hpp>
namespace tool
{
static const boost::regex esc("[\\^\\.\\$\\|\\(\\)\\[\\]\\{\\}\\*\\+\\?\\/\\\\]");
static const std::string rep("\\\\\\1&");
std::string regexEscape(const std::string& text)
{
std::string result;
result = boost::regex_replace(text, esc, rep, boost::match_default | boost::format_sed);
return result;
}
void splitByStr(const std::string& str, std::vector<std::string>& results, const std::string& seperator)
{
splitByRegex(str, results, regexEscape(seperator));
}
void splitByRegex(const std::string& str, std::vector<std::string>& results, const std::string& regex)
{
boost::regex reg(regex);
boost::sregex_token_iterator it(str.begin(), str.end(), reg, -1);
boost::sregex_token_iterator end;
while (it != end)
{
results.push_back(*it++);
}
}
}