给定一个旧式 const char *
指针和一个长度,有没有一种方法可以调用 std::regex_search()
而无需先复制其内容缓冲区到 std::string
?这是我遇到的问题的一个简单示例:
#include <regex>
int main()
{
const char *text = "123 foobar 456";
const size_t len = strlen(text);
const std::regex rx(" (.+)bar");
std::smatch what;
std::regex_search( text, text+len, what, rx); // <- problematic line
return 0;
}
我认为需要两个迭代器的第 5 个 std::regex_search() 是我需要的,但我不完全理解如何将指针转换为迭代器。当我尝试编译上面的代码时,我得到了这个:
g++ -std=c++11 test.cpp
test.cpp:11:45: error: no matching function for call to ‘regex_search(const char*&, const char*, std::smatch&, const regex&)’
/usr/include/c++/4.9/bits/regex.h:2131:5: note: template<class _Bi_iter, class _Alloc, class _Ch_type, class _Rx_traits> bool std::regex_search(_Bi_iter, _Bi_iter, std::match_results<_BiIter, _Alloc>&, const std::basic_regex<_CharT, _TraitsT>&, std::regex_constants::match_flag_type)
regex_search(_Bi_iter __s, _Bi_iter __e,
...还有更多错误!
能否将const char *
转换为必要的迭代器?我做错了吗?我是不是误解了它的工作原理?
最佳答案
您的代码中的错误是您使用了错误的 match_results
类型。当你有一个 std::string
对象并且你将 std::string::iterator
传递给时,应该使用 smatch
regex
函数。当您有原始 char const *
时,请改用 cmatch
。
改变
std::smatch what;
到
std::cmatch what;
关于c++ - 没有匹配函数调用 ‘regex_search(...)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28018959/