I am trying to validate IP address input in C. Here is my code
char* messType;
regex_t regex;
int regres;
char msgbuf[100];
/* Compile regular expression */
regres =
regcomp(®ex,
"^([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))."
"([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))."
"([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))."
"([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))$", 0);
if (regres)
{
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
regres = regexec(®ex, servIP, 0, NULL, 0);
if( regres == REG_NOMATCH )
{
puts("Invalid IP address");
exit(EXIT_FAILURE);
}
else
{
regerror(regres, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
However, this failed every IPV4 address I entered.
.since that's a special character in regex.regcompuses, but the man page says:'|'is used in an extended regular expression to select this subexpression or another, and the other subexpression matched., so maybe you need to giveREG_EXTENDEDas third parameter ofregcomp?