c - 为什么 C 的 regexec() 不匹配此模式,但 javascript 的 match() 有效?

标签 c regex

我有这个图案 [-]{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(&reg,
          "[-]{23}[ ]*Page[ ]*[0-9]*[-]{23}",
          REG_ICASE /* Don't differentiate case */
    );

int r = regexec(&reg,
         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(&reg, "[-]{23}[ ]*Page[ ]*([0-9]*)[-]{23}", REG_ICASE | REG_EXTENDED);
  /*                                ^------^ capture page number */
  r = regexec(&reg, 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/

相关文章:

c - 使用 Frama-c 分析带有 CMake 构建基础设施的项目

regex - Action Script 3.0 替换多行字符串中的所有出现

regex - Vi 编辑器 : Replacing in all lines except the ones that begin with #

c# - 正向回顾后正则表达式多次出现

c - 用 C 打开并读取 "large"gzip 压缩文件

c - C中的结构指针

整数表示的字符数组

C diff 各个函数或解析为单独的文件

regex - 从 Ant 任务中使用正则表达式删除新行

ios - 正则表达式 - 匹配替换时区分大小写