问题
I'm trying to make my way around with regular expressions an check if a String is an integer. I figured the pattern should be ^\d$ and I wrote a function to print an error if the argument is not fit:
regex_t regex;
void check_int(char *c)
{
check=regcomp(®ex,"^\d$",0);
if (check!=0)
{
perror("4th element on the line is not an integer!");
exit(5);
}
else printf("4th arg is a number.");
}
I'm not sure how regcomp works, I used it as I thought I should after checking some examples on the internet.
The trouble is it always says my string is a number, can't figure out why...
Added this, now always returns no match:
status = regexec(®ex, c, (size_t) 0, NULL, 0);
refree(®ex);
if(status!=0)
{
perror("..");
exit(5);
}
回答1:
There are several issues with your example:
regcomponly prepares the regular expression (check documentation: "Theregcomp()function shall compile the regular expression contained in the string pointed to by the pattern argument...")- as per documentation I'd assume your regular expression to be
"^[[:digit:]+]$" - your strings are terminated by
\n, so the end anchor didn't match here - you have to evaluate the result of regcomp in order to evaluate matches ("If it finds a match,
regexec()shall return 0; otherwise, it shall return non-zero indicating....") if a trailing white space is ok for you as well, use
[:space:]in additionvoid check_int(char *c) { int check=regcomp(®ex,"^[[:digit:]+]$",0); int status = regexec(®ex, c, (size_t) 0, NULL, 0); if (status !=0) { ....
Check CodePad for a full example.
回答2:
regcomp is used to compile the regular expression pattern, not match it against the input string. To match against the string, you need to use regexec. In this case, the return value of regcomp is always zero because the pattern seems to be compiled without error.
See this link a synopsis for each of the different functions and for usage examples.
来源:https://stackoverflow.com/questions/29182038/c-regular-expressions-regcomp