fnmatch 使用复杂模式 C [英] fnmatch usage with complicate pattern C

查看:50
本文介绍了fnmatch 使用复杂模式 C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只能匹配简单的模式,例如:"[0-9]"fnmatch("[0-9]", tocheck, 0).

I'm only able to match simple patterns like: "[0-9]" with fnmatch("[0-9]", tocheck, 0).

如果我尝试使用 ?. 甚至这些的组合更复杂的东西,我该如何使用 fnmatch?我看到有一些标志可以做到这一点,但我不知道如何使用,因为我对 C 相当陌生.

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.

我看到评论要求提供更多详细信息:

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);
}

如果我使用 patternOne 结果是 0 并且如果我更改字符串以匹配,结果会正确更改.但是,如果我使用 patternTwo,对于我传递给 fnmatch 的任何字符串,我都不会得到 0 结果.我需要在我的程序中匹配这样的东西.因为是大学考试,所以图案很复杂.

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.

推荐答案

将模式视为 shell glob 模式.鉴于:

Treat the pattern as a shell glob pattern. Given:

const char* patternTwo = ".?[a-z0-9]*?*[a-z0-9]";

"0" 不可能匹配它.匹配它的字符串的一个例子是:".XaX9"

There is no way "0" will match that. An example of a string that will match it would be: ".XaX9"

. 匹配 .
X 匹配 ?
a 匹配 [a-z0-9]
X 匹配 *?*
9 匹配 [a-z0-9]

. matches .
X matches ?
a matches [a-z0-9]
X matches *?*
9 matches [a-z0-9]

fnmatch()glob() 不同的原因是模式 "*"(作为普通的 glob匹配任何字符串)将无法匹配名为 ".profile" 的文件,因为点文件被视为隐藏文件(它是设计用于执行文件名匹配的函数).

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).

这篇关于fnmatch 使用复杂模式 C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆