C regular expressions, regcomp

旧城冷巷雨未停 提交于 2021-01-29 02:25:36

问题


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(&regex,"^\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(&regex, c, (size_t) 0, NULL, 0); 
refree(&regex); 
if(status!=0)
{
    perror("..");
    exit(5);
}

回答1:


There are several issues with your example:

  • regcomp only prepares the regular expression (check documentation: "The regcomp() 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 addition

    void check_int(char *c)
    {
      int check=regcomp(&regex,"^[[:digit:]+]$",0);
      int status = regexec(&regex, 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!