我试图使用lambda函数对boost::regex_replace
类型的std::string
进行调用。我可没办法把所有的类型都搞清楚。
typedef boost::basic_regex<char> regex;
typedef boost::match_results<char> smatch;
std::string text = "some {test} data";
regex re( "\\{([^\\}]*)\\}" );
text = boost::regex_replace( text, re, [&](smatch const & what) {
return what.str();
});
我使用的是typedef
,而不是标准名称,因为我有几个地方使用typedef/模板字符类型,而不是固定类型。
在这段代码中,我得到了一个错误:/usr/include/boost/regex/v4/match_results.hpp:68:77: error: no type named 'difference_type' in 'struct boost::re_detail::regex_iterator_traits<char>' BidiIterator>::difference_type difference_type;
发布于 2018-01-21 20:46:09
如果您有一个与C++11兼容的编译器,则不需要Boost或lambdas。
要实现相同的目标,只需使用std::regex
#include <iostream>
#include <regex>
int main()
{
std::string text = "some {test} data {asdf} more";
std::regex re("\\{([^\\}]*)\\}");
std::string out;
std::string::const_iterator it = text.cbegin(), end = text.cend();
for (std::smatch match; std::regex_search(it, end, match, re); it = match[0].second)
{
out += match.prefix();
out += match.str(); // replace here
}
out.append(it, end);
std::cout << out << std::endl;
}
当然,对于简单的文本替换,您可以只使用std::regex_replace()
,但它不能接受函式,只能接受静态格式字符串,可以选择使用组占位符:
std::string text = "some {test} data {asdf} more";
std::regex re("\\{([^\\}]*)\\}");
std::string out = std::regex_replace(text, re, "<$1>");
发布于 2018-01-21 19:56:27
正如文档中的结果参考页所示,boost::match_results
的第一个类型参数是BidirectionalIterator类型;因此,例如,标准类型为match_results<std::string::const_iterator>
。
要修复代码,您需要更正smatch
typedef,或者删除lambda参数what
上的引用,或者使其成为const引用:
typedef boost::basic_regex<char> regex;
typedef boost::match_results<std::string::const_iterator> smatch;
std::string text = "some {test} data";
regex re("\\{([^\\}]*)\\}");
text = boost::regex_replace(text, re, [] (const smatch& what) {
return what.str();
});
发布于 2018-01-21 14:41:37
smatch
类型有问题。我找不到一个带有typename的工作示例,但是使用C++14自动lambda参数解决了这个问题:
auto text = "some {test} data";
regex re( "\\{([^\\}]*)\\}" );
text = boost::regex_replace( text, re, [&](auto & what) {
return what.str();
});
https://stackoverflow.com/questions/48365482
复制相似问题