我有这个图案 [-]{23}[ ]*Page[ ]*[0-9]*[-]{23}
从 ----------------------- Page 1-----------------------
这样的字符串中提取页码它使用 javascript regex 实现工作正常:
var s = "----------------------- Page 1-----------------------";
alert( s.match(/[-]{23}[ ]*Page[ ]*[0-9]*[-]{23}/) != null);
match()
函数返回匹配的字符串值或 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。
it is possible to use
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;
}
关于c - 为什么 C 的 regexec() 不匹配此模式,但 javascript 的 match() 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9656161/