Search code examples
c++regexstringclr

How to use the result of std::regex_search?


I'm simply calling

std::smatch m;
if (std::regex_search 
  (std::string (strT.GetString ()), 
  m,
  std::regex ("((\\d[\\s_\\-.]*){10,13})")))
{
  ...
}

I can't for the life of me figure out how to extract the matched values from m.

EVERY SINGLE page on the subject writes it to cout which is worthless to me. I just want to get what's been captured in a string, but no matter what I try it crashes with a "string iterators incompatible" error message.

OK so I tried a few more things and got annoyed at a lot more, most notably about how the same code worked in online testers but not on my computer. I've come down to this

std::string s (strT.GetString ()) ;
std::smatch m;
if (std::regex_search (
    s, 
    m,
    std::regex ("((\\d[\\s_\\-.]*){10,13})")))
{
    std::string v = m[ 0 ] ;
}

working, but this

std::smatch m;
if (std::regex_search (
    std::string (strT.GetString ()), 
    m,
    std::regex ("((\\d[\\s_\\-.]*){10,13})")))
{
    std::string v = m[ 0 ] ;
}

Not Working For Some Reason (with the incompatible string iterator error thingy). There's surely some trick to it. I'll let someone who knows explain it.


Solution

  • You are correct that you can just assign the match to a std::string; you don't have to use the stream insertion feature.

    However, your third example crashes because std::smatch holds references/handles to positions in the original source data … which in your crashy case is the temporary strT.GetString() that went out of scope as soon as the regex was done (read here).

    Your second example is correct.

    I concede that the C++ regex implementation is not entirely intuitive at first glance.