Reputation: 15183
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.
Upvotes: 5
Views: 2783
Reputation: 69
Do a string replace with:
? -> .
* -> .*
. -> \.
This will do in most cases. If you come accross some special characters which can be in your text and have special meaning in regex, add more like the bottom line.
Upvotes: 0
Reputation: 106236
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).
Upvotes: 3
Reputation: 994251
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.
Upvotes: 1
Reputation: 156268
*
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.
Upvotes: 2