以下测试程序使用boost-regex中的命名捕获支持从日期中提取年,月和日字段(仅用于说明命名捕获的使用):
#include <boost/regex.hpp>
#include <boost/regex/icu.hpp>
#include <string>
#include <iostream>
int main(int argc, const char** argv)
{
std::string str = "2013-08-15";
boost::regex rex("(?<year>[0-9]{4}).*(?<month>[0-9]{2}).*(?<day>[0-9]{2})");
boost::smatch res;
std::string::const_iterator begin = str.begin();
std::string::const_iterator end = str.end();
if (boost::regex_search(begin, end, res, rex))
{
std::cout << "Day: " << res ["day"] << std::endl
<< "Month: " << res ["month"] << std::endl
<< "Year: " << res ["year"] << std::endl;
}
}
编译
g++ regex.cpp -lboost_regex -lboost_locale -licuuc
这个小程序将按预期产生以下输出:
$ ./a.out
Day: 15
Month: 08
Year: 2013
接下来,我用他们的u32regex对应物替换普通的正则表达式部分:
#include <boost/regex.hpp>
#include <boost/regex/icu.hpp>
#include <string>
#include <iostream>
int main(int argc, const char** argv)
{
std::string str = "2013-08-15";
boost::u32regex rex = boost::make_u32regex("(?<year>[0-9]{4}).*(?<month>[0-9]{2}).*(?<day>[0-9]{2})", boost::regex_constants::perl);
boost::smatch res;
std::string::const_iterator begin = str.begin();
std::string::const_iterator end = str.end();
if (boost::u32regex_search(begin, end, res, rex))
{
std::cout << "Day: " << res ["day"] << std::endl
<< "Month: " << res ["month"] << std::endl
<< "Year: " << res ["year"] << std::endl;
}
}
现在构建一个正在运行的程序会导致运行时异常,表明未初始化的shared_ptr:
$ ./a.out
a.out: /usr/include/boost/smart_ptr/shared_ptr.hpp:648: typename boost::detail::sp_member_access<T>::type boost::shared_ptr<T>::operator->() const [with T = boost::re_detail::named_subexpressions; typename boost::detail::sp_member_access<T>::type = boost::re_detail::named_subexpressions*]: Assertion `px != 0' failed.
我不是直接使用共享指针。
这是使用boost 1.58.1和gcc 5.3.1。
如何让u32regex版本的程序正常运行?