这是我的代码:
#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(®ex, inputName, 0);
// Regexec string that will match against user input
return_value = regexec(®ex, name, 0, NULL, 0);
if (return_value == REG_NOMATCH)
{
printf("Pattern not found.\n");
return 1;
}
else
{
printf("%s\n", name);
}
}
我尝试使用正则表达式匹配字符串。如您所见,我的代码运行得很好。有一个名为 Michael Corleone 的人储存在数组中。然后,当用户尝试输入:Michael或Corleone或Michael Corleone时,它将匹配并打印全名!
但问题在于大小写敏感性。如果用户尝试以小写输入这些名称,则无法匹配。
我尝试在 regcomp
内使用以下内容: regcomp(&regex,“[a-zA-Z] [inputName]”,0);
当我尝试以小写字母输入名称时,它可以工作。 但后来我发现,它也适用于输入其他姓名,例如 John , Leon 或 Angel 。所以我认为它匹配一切是字母。
请问你们有解决方案吗?谢谢!