gpt4 book ai didi

C 正则表达式不匹配

转载 作者:行者123 更新时间:2023-11-30 15:01:07 25 4
gpt4 key购买 nike

我在 http://www.regexpal.com/ 测试了以下正则表达式

([A-Z]{1}[a-z]+)+([_]{1}([A-Z]{1}[a-z]+)+)+[.][a-z]+

成功匹配以下文件名:

Butter_Butter.jpg    
JavaPiebald_Java_Piebald.jpg
LowWhitePied_Pied.jpg
Piebald_Piebald.jpg
SpinnerBlast_Spider_Pinstripe_Pastel.jpg
Caramel_Caramel.jpg
LightningPied_Pied_Axanthic.jpg
Pastel_Pastel.jpg
Spider_Spider.jpg
Spinner_Spider_Pinstripe.jpg

当我在以下 C 代码中实现正则表达式时,我没有收到任何匹配项:

#define COLLECTION_REGEX "([A-Z]{1}[a-z]+)+([_]{1}([A-Z]{1}[a-z]+)+)+[.][a-z]+"

int is_valid_filename(char *filename)
{
regex_t regex;
int i, match;
char msgbuf[100];

match = 1;
i = regcomp(&regex, COLLECTION_REGEX, 0);

if (i)
{
perror("Could not compile regex");
}
else
{
match = regexec(&regex, filename, 0, NULL, 0);

if (!match)
{
puts("Match");
}
else if (match == REG_NOMATCH)
{
puts("No match");
}
else
{
regerror(match, &regex, msgbuf, sizeof(msgbuf));
puts(msgbuf);
}
}

regfree(&regex);

return match;
}

后续执行:

./a.out 
No match
No match
No match
No match
No match
No match
No match
No match
No match
No match

正则表达式看起来正确,我不确定为什么会得到这些结果。

<小时/>

GDB 的输出:

Breakpoint 1, is_valid_filename (filename=0x609050 "Piebald_Piebald.jpg") at crp-web-builder.c:76
76 match = regexec(&regex, filename, 0, NULL, 0);
(gdb) continue
Continuing.
No match

Breakpoint 1, is_valid_filename (filename=0x609460 "LightningPied_Pied_Axanthic.jpg") at crp-web-builder.c:76
76 match = regexec(&regex, filename, 0, NULL, 0);
(gdb) continue
Continuing.
No match

Breakpoint 1, is_valid_filename (filename=0x609870 "SpinnerBlast_Spider_Pinstripe_Pastel.jpg") at crp-web-builder.c:76
76 match = regexec(&regex, filename, 0, NULL, 0);
(gdb) continue
Continuing.
No match

最佳答案

感谢乔纳森·莱夫勒。该行:

i = regcomp(&regex, COLLECTION_REGEX, 0);

应该是:

i = regcomp(&regex, COLLECTION_REGEX, REG_EXTENDED);

关于C 正则表达式不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41652352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com