[英]why regexec() of C does not match this pattern, but match() of javascript works?
我有这种模式[-]{23}[ ]*Page[ ]*[0-9]*[-]{23}
从----------------------- Page 1-----------------------
这样的字符串中提取页码----------------------- Page 1-----------------------
使用javascript正则表达式实现它可以正常工作:
var s = "----------------------- Page 1-----------------------";
alert( s.match(/[-]{23}[ ]*Page[ ]*[0-9]*[-]{23}/) != null);
match()
函数返回匹配的字符串值,如果pattern与string不匹配,则返回null
。 以上代码显示为true
我的C代码:
#include <assert.h>
#include <sys/types.h>
#include <regex.h>
//...
regex_t reg;
regmatch_t match;
char * line = "----------------------- Page 1-----------------------";
regcomp(®,
"[-]{23}[ ]*Page[ ]*[0-9]*[-]{23}",
REG_ICASE /* Don't differentiate case */
);
int r = regexec(®,
line, /* line to match */
1, /* size of captures */
&match,
0);
if( r == 0) { printf("Match!"); } else { printf("NO match!"); }
上面的if语句打印NO match!
我不知道如何解决这个问题。 提前致谢。
要使正则表达式库识别完整的正则表达式,请在regcomp
标志中使用REG_EXTENDED。
有可能使用
groups
吗?
你的意思是捕捉团体? 像这样?
#include <assert.h>
#include <stdio.h>
#include <sys/types.h>
#include <regex.h>
int main(void) {
int r;
regex_t reg;
regmatch_t match[2];
char *line = "----------------------- Page 1-----------------------";
regcomp(®, "[-]{23}[ ]*Page[ ]*([0-9]*)[-]{23}", REG_ICASE | REG_EXTENDED);
/* ^------^ capture page number */
r = regexec(®, line, 2, match, 0);
if (r == 0) {
printf("Match!\n");
printf("0: [%.*s]\n", match[0].rm_eo - match[0].rm_so, line + match[0].rm_so);
printf("1: [%.*s]\n", match[1].rm_eo - match[1].rm_so, line + match[1].rm_so);
} else {
printf("NO match!\n");
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.