samedi 2 mars 2019

How to match multiple patterns with a regex in C++ 11

Suppose there is a string named path that needs to match multiple patterns. The regular expression string is as follows:

std::string regexString="(/api/Attachment)|(/api/Attachment/upload)|(/api/Attachment/download)|(/api/v1/ApiTest)|(/api/v1/ApiTest/get/[^/]*/[^/]*)|(/api/v1/ApiTest/[^/]*/List)";

The matching code is as follows:

std::smatch result;
if (std::regex_match(path, result, regexString))
{
    for (size_t i = 1; i < result.size(); i++)
    {
        /// Question: Is there any better way to find the sub-match index without using a loop?
        if (!result[i].matched)
            continue;
        if (result[i].str() == path)
        {
            std::cout<<"Match a pattern with index "<<i<<std::endl;
            /// Do something with it;
            break;
        }
     }
 }
 else
 {
     std::cout<<"Match none"<<std::endl;
 }

The above program works, but considering a large number of patterns, the loop in it is a bit ugly and inefficient. As the comments in the code show, my question is is there a way to find the sub-match index without using loops?

Any comments would be greatly appreciated, thank you!

Aucun commentaire:

Enregistrer un commentaire