加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么regexec()在posix c总是返回第一个匹配,怎么能返回所有的

发布时间:2020-12-16 02:59:50 所属栏目:百科 来源:网络整理
导读:现在当我想要返回str中的所有匹配位置,如: abcd123abcd123abcd 假设我想要得到所有的“abcd”,我必须使用regexec(),得到第一个位置:0,3,然后我会使用: 123abcd123abcd 作为新的字符串再次使用regexec(),等等. 我读了关于regexec()的手册,它说: int regex
现在当我想要返回str中的所有匹配位置,如:
abcd123abcd123abcd

假设我想要得到所有的“abcd”,我必须使用regexec(),得到第一个位置:0,3,然后我会使用:

123abcd123abcd

作为新的字符串再次使用regexec(),等等.
我读了关于regexec()的手册,它说:

int regexec(const regex_t *preg,const char *string,size_t nmatch,regmatch_t pmatch[],int eflags);
nmatch and pmatch are used to provide information regarding the location of any 
matches.

但为什么这不工作?
这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>

int main(int argc,char **argv)
{
   int i = 0;
   int res;
   int len;
   char result[BUFSIZ];
   char err_buf[BUFSIZ];
   char* src = argv[1];  

   const char* pattern = "<[^,;]+>";
   regex_t preg;

   regmatch_t pmatch[10];

   if( (res = regcomp(&preg,pattern,REG_EXTENDED)) != 0)
   {
      regerror(res,&preg,err_buf,BUFSIZ);
      printf("regcomp: %sn",err_buf);
      exit(res);
   }

   res = regexec(&preg,src,10,pmatch,REG_NOTBOL);
   //~ res = regexec(&preg,0);
   //~ res = regexec(&preg,REG_NOTEOL);
   if(res == REG_NOMATCH)
   {
      printf("NO matchn");
      exit(0);
   }
   for (i = 0; pmatch[i].rm_so != -1; i++)
   {
      len = pmatch[i].rm_eo - pmatch[i].rm_so;
      memcpy(result,src + pmatch[i].rm_so,len);
      result[len] = 0;
      printf("num %d: '%s'n",i,result);
   }
   regfree(&preg);
   return 0;
}

./regex 'hello,world'

输出:

num 0: 'hello'

这是我的尊重输出:

num 0: 'hello'
num 1: 'world'

解决方法

regexec执行正则表达式匹配.一旦匹配被发现regexec将返回零(即成功匹配).参数pmatch将包含有关该匹配的信息.第一个数组索引(即零)将包含整个匹配,后续数组索引包含有关捕获组/子表达式的信息.

展示:

const char* pattern = "(w+) (w+)";

匹配“hello world”将输出:

num 0: 'hello world'  - entire match
num 1: 'hello'        - capture group 1
num 2: 'world'        - capture group 2

(见action)

在大多数正则表达式环境中,您可以通过使用全局修饰符获得所寻求的行为:/ g.正则表达式不将此修饰符提供为标志,也不支持修饰符.因此,您将必须循环,同时regexec从上一个匹配的最后一个字符开始返回零,以获得所有匹配.

全局修饰符也不可用于PCRE库(着名的正则表达式C库). PCRE手册页有这样的说法:

By calling pcre_exec() multiple times with appropriate arguments,you can mimic Perl’s /g option

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读