9

Given an old-style const char * pointer and a length, is there a way to call std::regex_search() on it without first copying the contents of the buffer into a std::string? Here is a simple example of the problem I have:

#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;
}

I thought the 5th std::regex_search() that takes two iterators is what I need, but I'm not fully understanding how to convert pointers to iterators. When I try to compile the code above, I get this:

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,

...and a lot more errors!

Can const char * be converted to the necessary iterator? Did I do it wrong? Am I misunderstanding how this works?

4

1 回答 1

13

您的代码中的错误是您使用了错误的match_results类型。当你有一个对象并且你将s 传递给函数smatch时应该使用它。当您使用 raw 时,请改用。std::stringstd::string::iteratorregexchar const *cmatch

改变

std::smatch what;

std::cmatch what;

现场演示

于 2015-01-19T06:25:32.110 回答