Search code examples
c++regexglob

How to use regexp to perform a glob in C/C++ (Linux)


I need to match simple some simple glob patterns that include only * and ?. It occurred to me that I could transform the input pattern into a regexp - the only problem is I'm not familiar with regexp enough to know the replacements.

Essentially, I need an implementation for:

std::string getRexExpForGlob(const std::string& globPattern);

Note these matches aren't used for anything to do with the filesystem, so POSIX glob won't do.


Solution

  • Depending on your OS, you may have <fnmatch> with int fnmatch(const char* pattern, const char* string, int flags). This allows glob patterns against arbitrary strings, and a few extra flags to allow flexibility beyond that needed for filename matching.

    Otherwise, glob's * and ? are equivalent to regexp .* and . respectively. (Globs can also have [] alternatives but you've said yours don't).