Reputation: 109
This is my code:
#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);
}
}
I try to match a string using regex. As you can see, my code works pretty well. There's a person store in array named Michael Corleone. Then, when user try to input: Michael or Corleone or Michael Corleone it will matched and print the full name!
But the problem is case-sensitivity. If user try to input those name in lowercase it will failed.
I try to use this inside regcomp
: regcomp(®ex, "[a-zA-Z][inputName]", 0);
It works when i try to type the name in lowercase. But then i found out, it also works when i type another name like John, Leon, or Angel. So, i think it match everything that is alphabets.
Do you guys have the solution, please? Thank You!
Upvotes: 3
Views: 548
Reputation: 627083
You need to replace the last argument to regcomp
function (which is 0
now) with REG_ICASE
:
return_value = regcomp(®ex, inputName, REG_ICASE); // 0 replaced with REG_ICASE
See the C demo.
From the regcomp
documentation:
REG_ICASE
Do not differentiate case. Subsequentregexec()
searches using this pattern buffer will be case insensitive.
Upvotes: 4