Mathieu Corti Mathieu Corti - 10 months ago 84
C++ Question

Regex matching groups boost c++

[Noob Corner]

I'm trying to catch a group with boost regex depending on the string that matched and I think I'm using a wrong way.

boost::regex expr(R"(:?(:?\busername *(\S*))|(:?\bserver *(\S*))|(:?\bpassword *(\S*)))");
std::vector<std::string > vec = { "server", "username myusername", "password mypassword" };

for (auto &elem : vec)
if (boost::regex_match(elem, expr, boost::match_extra))
boost::smatch what;
boost::regex_search(elem, what, expr);

std::cout << "Match 1 (username) : " << what[1].str() << std::endl;
std::cout << "Match 2 (server) : " << what[2].str() << std::endl;
std::cout << "Match 3 (password) : " << what[3].str() << std::endl;

I want something like :


Match 1 (username) : NULL

Match 2 (server) :

Match 3 (password) : NULL

I searched on internet but I have not found clear answers regarding the identification of capturing groups.


Answer Source

You actually have 6 and not 3 matching groups.

Your regular expression is organized in such a manner that the odd matching groups will match a key-value (i.e.: username myusername) while the even matching groups will match the actual value (i.e.: myusername).

So you have to look for groups 2, 4 and 6 to get the username, server and password values.