Mathieu Corti Mathieu Corti - 1 month ago 15
C++ Question

Regex matching groups boost c++

[Noob Corner]

Hello,
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 my.server.eu", "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 :

server my.server.eu



Match 1 (username) : NULL

Match 2 (server) : my.server.eu

Match 3 (password) : NULL



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

Thanks

Answer

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.

Comments