1

[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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Wimps
  • 359
  • 1
  • 3
  • 11
  • You meant to use `(?:`, not `(:?`, right? Sorry, your question is somewhat unclear. – Wiktor Stribiżew Nov 03 '16 at 17:44
  • What is sure, your regex can be written as `expr(R"(\b(?:username *(\S*)|server *(\S*)|password *(\S*)))")`. When testing, I get `Match 1 (username) : // Match 2 (server) : my.server.eu // Match 3 (password) :` – Wiktor Stribiżew Nov 03 '16 at 17:59
  • Thanks @WiktorStribiżew that was that, I reversed the ? and the : This plus the named groups capture have resolved my issue. – Wimps Nov 04 '16 at 09:54
  • Good, but you seem to be happy with the current answer. I will refrain from posting the code and my explanation. – Wiktor Stribiżew Nov 04 '16 at 10:06

1 Answers1

1

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.

Pedro Boechat
  • 2,446
  • 1
  • 20
  • 25