你可以序列化一个 boost::regex:
#include <string>
#include <iostream>
#include <sstream>
#include <boost/regex.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/split_free.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
namespace boost
{
namespace serialization
{
template<class Archive, class charT, class traits>
inline void save(Archive & ar,
const boost::basic_regex<charT, traits> & t,
const unsigned int /* file_version */)
{
std::basic_string<charT> str = t.str();
typename boost::basic_regex<charT, traits>::flag_type flags = t.flags();
// typename boost::basic_regex<charT, traits>::locale_type loc = t.getloc();
ar & str;
ar & flags;
// ar & loc;
}
template<class Archive, class charT, class traits>
inline void load(Archive & ar,
boost::basic_regex<charT, traits> & t,
const unsigned int /* file_version */)
{
std::basic_string<charT> str;
typename boost::basic_regex<charT, traits>::flag_type flags;
// typename boost::basic_regex<charT, traits>::locale_type loc;
ar & str;
ar & flags;
// ar & loc;
t.assign(str, flags);
// t.imbue(loc);
}
template<class Archive, class charT, class traits>
inline void serialize(Archive & ar,
boost::basic_regex<charT, traits> & t,
const unsigned int file_version)
{
boost::serialization::split_free(ar, t, file_version);
}
}
}
int main(int argc, char ** argv)
{
std::stringstream os;
{
boost::regex re("<a\\s+href=\"([\\-:\\w\\d\\.\\/]+)\">");
boost::archive::text_oarchive oar(os);
oar & re;
}
os.seekg(std::ios_base::beg);
boost::regex re;
boost::cmatch matches;
boost::archive::text_iarchive iar(os);
iar & re;
boost::regex_search("<a href=\"https://stackoverflow.com/questions/18752807/save-serialize-boost-or-std-regexes\">example</a>", matches, re);
std::cout << matches[1] << std::endl;
}
但这并不意味着与从字符串重构正则表达式相比,您将获得任何性能提升。
注意:为简单起见,我省略了 std::locale 内容