I was trying to write a simple c program to check if a path name has a ".jpg" or ".jpeg" suffix. Here is my program:
我试图编写一个简单的c程序来检查路径名是否有“.jpg”或“.jpeg”后缀。这是我的计划:
#include <stdio.h>
#include <string.h>
#include <regex.h>
regex_t regex;
static int is_acceptable_format(const char *path) {
int reti = regexec(®ex, path, 0, NULL, 0);
if (!reti) {
return 1;
} else if (reti == REG_NOMATCH) {
return 0;
} else {
char msgbuf[100];
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
printf("Regex match failed: %s\n", msgbuf);
return 0;
}
}
static void init_accpetable_format() {
if (regcomp(®ex, "\\.JP(E?)G$", REG_ICASE)) {
printf("Could not compile regex\n");
}
}
main()
{
const char *path = "/sample_img.jpg";
init_accpetable_format();
printf("path=\"%s\" is %s\n",
path, is_acceptable_format(path) ? "acceptable" : "unacceptable");
}
I expected my program to return "acceptable" but it returned "unacceptable" instead. If I make my regex be "\.JPG$", the result became "acceptable".
我希望我的程序可以返回“可接受的”,但它却返回“不能接受”。如果我将regex设置为“\”。JPG$,结果变得“可接受”。
I thought question mark (?) in regex means 0 or 1 times regex rule. But why doesn't it work?
我认为在regex中问号(?)的意思是0或1乘以regex规则。但是为什么它不工作呢?
1 个解决方案
#1
3
? is part of the extended POSIX regexes, not the basic POSIX regex: http://en.wikipedia.org/wiki/Regular_expression#POSIX_basic_and_extended
吗?是扩展POSIX regexes的一部分,而不是基本的POSIX regex: http://en.wikipedia.org/wiki/Regular_expression#POSIX_basic_and_extended吗
As such, you need to add the flag REG_EXTENDED to your regexcomp, like in this example : http://www.lemoda.net/c/unix-regex/
因此,您需要在regexcomp中添加标记REG_EXTENDED,比如在这个示例中:http://www.lemoda.net/c/unix regex/。
#1
3
? is part of the extended POSIX regexes, not the basic POSIX regex: http://en.wikipedia.org/wiki/Regular_expression#POSIX_basic_and_extended
吗?是扩展POSIX regexes的一部分,而不是基本的POSIX regex: http://en.wikipedia.org/wiki/Regular_expression#POSIX_basic_and_extended吗
As such, you need to add the flag REG_EXTENDED to your regexcomp, like in this example : http://www.lemoda.net/c/unix-regex/
因此,您需要在regexcomp中添加标记REG_EXTENDED,比如在这个示例中:http://www.lemoda.net/c/unix regex/。