问题
I'm only able to match simple patterns like: "[0-9]"
with fnmatch("[0-9]", tocheck, 0)
.
If I try something more complicated with ?
or .
or even a combination of these how do I use fnmatch
?
I saw there are some flags that can do the trick, but I don't know how to use because I'm fairly new to C.
EDIT: I saw the comment asking to give more details:
#include <stdio.h>
#include <fnmatch.h>
int main(int argc, char **argv) {
const char *patternOne = "[0-9]";
const char *patternTwo = ".?[a-z0-9]*?*[a-z0-9]";
int res = fnmatch(patternTwo, "0", 0);
printf("Result: %d\n", res);
}
If I use patternOne
the result is 0
and if I change the string to match, the result change correctly.
However if I use patternTwo
I never get the 0
result for whatever string I pass to fnmatch
.
I need to match something like this in my program. It is for an university exam, so the patterns are very intricate.
回答1:
Treat the pattern as a shell glob pattern. Given:
const char* patternTwo = ".?[a-z0-9]*?*[a-z0-9]";
There is no way "0"
will match that. An example of a string that will match it would be: ".XaX9"
.
matches.
X
matches?
a
matches[a-z0-9]
X
matches*?*
9
matches[a-z0-9]
The reason fnmatch()
is different from glob()
is so that the pattern "*"
(which as a normal glob would match any string) will fail to match a file named ".profile"
because dot files are treated as hidden (it is function designed to perform a file name match).
来源:https://stackoverflow.com/questions/50591907/fnmatch-usage-with-complicate-pattern-c