Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

c++ - no matching function for call to ‘regex_search(...)'

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error in your code is that you're using the wrong match_results type. smatch is supposed to be used when you have an std::string object and you're passing std::string::iterators to the regex function. When you have raw char const *s use cmatch instead.

Change

std::smatch what;

to

std::cmatch what;

Live demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...