Search code examples
c++regexglob

Pattern Matching on every element in the vector


I have a function which looks like this:

bool ExpandWildCard(vector<string>& names, vector<string>& result, string& wildcard) 
{
}

Here, I want to match the wildcard with each element in the vector names and if it does match, then add the element in names to the result vector.

Of course, if the wildcard is *, I could just add everything from names to results. Also I'm just trying to implement the * wildcard for now.

How can I do this in C++?

One way I thought of doing this was using find() algorithm but I am not sure I would match wildcards using that?


Solution

  • It looks like you are looking for some combination of std::copy_if and maybe std::regex_match:

    bool ExpandWildCard(vector<string>& names, vector<string>& result, string& wildcard) {
      auto oldsize = result.size();
      std::copy_if(std::begin(names), std::end(names),
        std::back_inserter(result),
        [&](string const& name) {
          return std::regex_match(name, make_regex(wildcard));
        }
      );
    
      return (result.size() > oldsize);
    }
    

    Where make_regex would be the function you need to implement to convert your string into a std::regex.