Why is C ++ regex code that works with "cmatch" throw an exception with "smatch"?

I am new to C ++ regular expressions and can't get them to work with strings instead of char *. The examples I've seen so far have always been for c lines.

My real program, which I’m not even trying to show here, uses auxiliary matches, but I couldn’t get them to work, so I tried to change a very simple working example, but it doesn’t work either. I am using Visual Studio 2010 Ultimate.

Original - working code:

const char *first = "abcd"; 
const char *last = first + strlen(first); 
std::cmatch mr; 
std::regex rx("abc"); 
std::regex_constants::match_flag_type fl = std::regex_constants::match_default;

std::cout << "search(f, l, \"abc\") == " << std::boolalpha 
          << regex_search(first, last, mr, rx) << std::endl; 
std::cout << "  matched: \"" << mr.str() << "\"" << std::endl; 

std::cout << "search(\"xabcd\", \"abc\") == " << std::boolalpha
          << regex_search("xabcd", mr, rx) << std::endl; 
std::cout << "  matched: \"" << mr.str() << "\"" << std::endl;

Modified Code:

const string first = "abcd";     // char * => string
std::smatch mr;                  // cmatch => smatch
std::regex rx(string("abc")); 
std::regex_constants::match_flag_type fl = std::regex_constants::match_default;

               // this works:
std::cout << "search(f, l, \"abc\") == " << std::boolalpha 
          << regex_search(first, mr, rx) << std::endl; 
std::cout << "  matched: \"" << mr.str() << "\"" << std::endl; 

               // after the next line executes mr seems good to me:
               // mr[0] = {3, matched:true, first="abcd", second="d",...}
std::cout << "search(\"xabcd\", \"abc\") == " << std::boolalpha
          << regex_search(string("xabcd"), mr, rx) << std::endl; 
               // but the following line gives the error
               // "Debug assertion failed"
               // Expression: string iterators incompatible
std::cout << "  matched: \"" << mr.str() << "\"" << std::endl;

It is strange that one part of the modified code works, and the next part throws an exception. I even tried using mr [0] .str () but got the same error message. Could you help me solve this problem?

+5
1

- .

smatch , .

regex_search(string("xabcd"), mr, rx) , ;.

, mr , . string , mr.

+10

All Articles