C语言中使用正则表达式匹配字符串(忽略大小写)

时间:2021-04-23 16:36:09

标签: c regex

这是我的代码:

#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <regex.h>

int main(void)
{
    char name[]= "Michael Corleone";
    char inputName[40];

    regex_t regex;
    int return_value;

    printf("Enter name: ");
    fgets(inputName, sizeof(inputName), stdin);
    // Remove new line from fgets
    inputName[strcspn(inputName, "\n")] = 0;
    
    // Regcomp string input by user as pattern
    return_value = regcomp(&regex, inputName, 0);
    // Regexec string that will match against user input
    return_value = regexec(&regex, name, 0, NULL, 0);

    if (return_value == REG_NOMATCH)
    {
        printf("Pattern not found.\n");
        return 1;
    }
    else
    {
        printf("%s\n", name);
    }
}

我尝试使用正则表达式匹配字符串。如您所见,我的代码运行良好。数组中有一个名为 Michael Corleone 的人员存储。然后,当用户尝试输入:MichaelCorleoneMichael Corleone 时,它会匹配并打印全名!

但问题是区分大小写。如果用户尝试以小写输入这些名称,它将失败。

我尝试在 regcomp 中使用它:regcomp(&regex, "[a-zA-Z][inputName]", 0); 当我尝试以小写形式输入名称时它会起作用。但后来我发现,当我输入另一个名字(如 JohnLeonAngel)时,它也可以使用。所以,我认为它匹配所有字母。

请问你们有解决方案吗?谢谢!

1 个答案:

答案 0 :(得分:4)

您需要将 https://www.googleapis.com/youtube/v3/search?maxResults=50&part=id&type=video&channelId=UCgdHSFcXvkN6O3NXvif0-pA 函数的最后一个参数(现在是 regcomp)替换为 0

REG_ICASE

参见C demo

来自regcomp documentation

<块引用>

return_value = regcomp(&regex, inputName, REG_ICASE); // 0 replaced with REG_ICASE
不区分大小写。使用此模式缓冲区的后续 REG_ICASE 搜索将不区分大小写。