[英]Posix regular expression in C
I am working on this code where i have to compile some regular expression and use these compiled versions multiple times on different strings. 我在这段代码上工作,我必须编译一些正则表达式,并在不同的字符串上多次使用这些编译后的版本。 So i decided to make a function where i could pass these compiled version for matching the string. 所以我决定做一个函数,让我可以传递这些编译后的版本来匹配字符串。 My problem is that when i pass the compiled version in the function its showing a match but setting the regmatch_t structure fields to 0. However if i use them within the same function i am getting correct results. 我的问题是,当我在函数中传递编译后的版本时,它显示匹配项,但将regmatch_t结构字段设置为0。但是,如果我在同一函数中使用它们,则会得到正确的结果。
void match_a(regex_t *a,char *str)
{
regmatch_t match_ptr;
size_t nmatch;
regexec(a,str,nmatch,&match_ptr,0);
}
int main()
{
regex_t a;
regmatch_t match_ptr;
size_t nmatch;
char *str="acbdsfs";
regcomp(&a,str,RE_EXTENDED);
match_a(&a,str);
}
This is the general structure of the code.Please suggests any ways to debug this program 这是代码的一般结构。请提出调试该程序的任何方法
I'm not sure you understand how to use regexec
. 我不确定您是否了解如何使用regexec
。 The nmatch
argument tells regexec
the number of regmatch_t
objects you have provided. nmatch
参数告诉regexec
您提供的regmatch_t
对象的数量。 You haven't initialised the nmatch
variable so it could be any indeterminate value, which will likely lead to a crash at some stage, or it may be 0
in which case the regexec
function is defined to ignore the pmatch
argument. 您尚未初始化nmatch
变量,因此它可以是任何不确定的值,这可能会在某个阶段导致崩溃,或者它可能为0
在这种情况下, regexec
函数被定义为忽略 pmatch
参数。
If you want only one regmatch_t
result, try this: 如果只需要一个regmatch_t
结果,请尝试以下操作:
void match_a(regex_t *a,char *str)
{
regmatch_t match;
size_t nmatch = 1;
regexec(a, str, nmatch, &match, 0);
}
If you want up to 10 regmatch_t
(for regular expressions with groups etc), try this: 如果您最多需要10个regmatch_t
(用于具有组等的正则表达式),请尝试以下操作:
void match_a(regex_t *a,char *str)
{
regmatch_t matches[10];
size_t nmatch = 10;
regexec(a, str, nmatch, matches, 0);
}
For more information, read this documentation . 有关更多信息,请阅读本文档 。
Why matches is not filled in position 1? 为什么比赛没有填写在位置1?
regex_t a;
regcomp(&a,"brasil",REG_ICASE);
regmatch_t matches[2];
size_t nmatch = 2;
regexec(&a,"brasil brasil",nmatch,matches,0);
int x;
for(x=0;x<2;x++)
printf("%i\n",matches[x].rm_so);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.