c++ - 没有匹配函数调用 ‘regex_search(...)'

标签 c++ regex c++11 g++4.9

给定一个旧式 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;

Live demo

关于c++ - 没有匹配函数调用 ‘regex_search(...)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28018959/

相关文章:

c++ - 变量是大小为 1 的数组吗?

c++ - 使用 Clion 的 C++ 简单程序 "expected ` ,' or ` .. .' before ' & &' token"

c++ - 编译时映射和逆映射值

python - 编程竞赛,如输入验证器

c++ - C++ 网络库

javascript - 需要从javascript中的长字符串中替换字符串

用于链接字符串中的 url 的 C# 代码

c++ - 通过引用返回静态 vector 很慢

c++ - Clang、std::shared_ptr 和 std::less/operator<

c++ - 将元组参数转发给 VS2012 中的函数