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

3

这是我的代码:

#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); 当我尝试以小写字母输入名称时,它可以工作。 但后来我发现,它也适用于输入其他姓名,例如 John Leon Angel 。所以我认为它匹配一切是字母。

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

1个回答

4

您需要将regcomp函数的最后一个参数(现在为0)替换为REG_ICASE

return_value = regcomp(&regex, inputName, REG_ICASE); // 0 replaced with REG_ICASE

请看C示例
来自regcomp文档:

REG_ICASE
不区分大小写。使用此模式缓冲区进行后续regexec()搜索将不区分大小写。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接