Earlier I was working on a command line utility that needed to take a list of potentially wildcarded files as input. I didn't want a fully blown regular expression as the input, just the normal ? and * options.
I decided that the quickest way to do this was to convert the wildcarded filename to a regular expression and then use the STL std::regex to do the matching.
Here is a quick way to do it.
#pragma once
#include <regex>
#include <string>
inline std::regex convert_file_wildcards_to_regex(std::string file_pattern)
{
std::string pattern;
for (auto c : file_pattern)
{
switch (c)
{
default:
pattern += c;
break;
case '.':
pattern += "\\.";
break;
case '\\':
pattern += "\\\\";
break;
case '?':
pattern += ".";
break;
case '*':
pattern += ".*";
break;
}
}
return std::regex(pattern, std::regex_constants::ECMAScript | std::regex_constants::icase);
}