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.
*
in a glob pattern is equivalent to .*
in regex. ?
is equivalent to .
. In most regex dialects, .
does not match a newline by default, and so if you need it to match that character, check your library for how to set that flag.
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).
In regular expressions, .
represents any single character. This maps to ?
in glob patterns. Similarly, .*
represents any sequence of characters, which maps to *
in glob patterns. You should be able to write a workable function from that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.