I’m trying to match a string “123,1234” using regex.h. Following pattern does the job:
"^[0-9]\{1,\},[0-9]\{1,\}$"
If I’m giving it as a commandline argument it works fine. But when I use it inside C code it does not work. Probably because identifying backward slashes as escape characters.
Sample Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
int main (int argc, char * argv[]){
regex_t regex;
int reti;
char msgbuf[100];
char * string, * pattern;
string = "123,1234";
pattern = "^[0-9]\{1,\},[0-9]\{1,\}$";
if(regcomp(®ex, pattern, 0))
{
fprintf(stderr, "Could not compile regex\n");
exit(107);
}
if(!(reti = regexec(®ex, string, 0, NULL, 0)))
{
printf("MATCH\n");
}
else if(reti == REG_NOMATCH)
{
printf("NO MATCH\n");
}
else
{
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(107);
}
regfree(®ex);
return 0;
}
How can I solve this?
Your regular expression is an ERE not a BRE, so you need to pass the
REG_EXTENDEDflag toregcomp. Then, as others have said, remove the backslashes too.