Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C正则表达式,regcomp_C_Regex - Fatal编程技术网

C正则表达式,regcomp

C正则表达式,regcomp,c,regex,C,Regex,我试图用正则表达式检查字符串是否为整数。我认为模式应该是^\d$,并且我编写了一个函数,在参数不合适时打印错误: 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);

我试图用正则表达式检查字符串是否为整数。我认为模式应该是
^\d$
,并且我编写了一个函数,在参数不合适时打印错误:

 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.");
 }
我不确定
regcomp
是如何工作的,我在网上查看了一些示例后,按照我的想法使用了它。 问题是它总是说我的字符串是一个数字,不知道为什么

添加此选项后,现在始终不返回匹配项:

status = regexec(&regex, c, (size_t) 0, NULL, 0); 
refree(&regex); 
if(status!=0)
{
    perror("..");
    exit(5);
}

regcomp
用于编译正则表达式模式,而不是将其与输入字符串匹配。要与字符串匹配,需要使用
regexec
。在这种情况下,
regcomp
的返回值始终为零,因为模式似乎编译时没有错误


请参阅每个不同功能的概要和用法示例。

您的示例中有几个问题:

  • regcomp
    仅准备正则表达式(选中:“函数
    regcomp()
    应编译模式参数所指向字符串中包含的正则表达式…”)
  • 根据,我假设您的正则表达式为“
    ”^[:digit:][+]$”
  • 您的字符串被
    \n
    终止,因此此处的结束锚不匹配
  • 为了评估匹配项,您必须评估(“如果它找到匹配项,
    regexec()
    将返回0;否则,它将返回非零表示…”)
  • 如果尾随空白也适合您,则另外使用
    [:space::

    void check_int(char *c)
    {
      int check=regcomp(&regex,"^[[:digit:]+]$",0);
      int status = regexec(&regex, c, (size_t) 0, NULL, 0);
    
      if (status !=0)
      {
        ....
    

检查代码板中的a。

I添加了:
status=regexec(®ex,c,(size\u t)0,NULL,0);refree(®ex);if(status!-0){perror(“..”;exit(5);}}}
但现在它总是说它不是一个数字