Put first boost::regex match into a string

Tomáš Zato - Reinstate Monica picture Tomáš Zato - Reinstate Monica · Mar 21, 2013 · Viewed 23.6k times · Source

Somehow, I've failed to find out, how to put only the first occurrence or regular expression to string. I can create a regex object:

static const boost::regex e("<(From )?([A-Za-z0-9_]+)>(.*?)"); 

Now, I need to match ([A-Za-z0-9_]+) to std::string, say playername.

std::string chat_input("<Darker> Hello");
std::string playername = e.some_match_method(chat_input, 1);   //Get contents of the second (...)

What have I missed?
What should be instead of some_match_method and what parameters should it take?

Answer

Loghorn picture Loghorn · Mar 21, 2013

You can do something like this:

static const regex e("<(From )?([A-Za-z0-9_]+)>(.*?)");
string chat_input("<Darker> Hello");
smatch mr;
if (regex_search(begin(chat_input), end(chat_input), mr, e)
    string playername = mr[2].str();   //Get contents of the second (...)

Please note that regex is part of C++11, so you don't need boost for it, unless your regular expression is complex (as C++11 and newer still has difficulties processing complex regular expressions).