的C为什么regexec()不匹配此模式,但匹配()的JavaScript的作品? [英] why regexec() of C does not match this pattern, but match() of javascript works?

查看:159
本文介绍了的C为什么regexec()不匹配此模式,但匹配()的JavaScript的作品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种模式 [ - ] {23} [] *页[] * [0-9] * [ - ] {23} 来提取页码从像的字符串-----------------------页面1 --------------- -------- 它使用JavaScript正则表达式实现正常工作:

I have this pattern [-]{23}[ ]*Page[ ]*[0-9]*[-]{23}to extract the page number from an string like ----------------------- Page 1----------------------- it works fine using javascript regex implementation:

var s = "----------------------- Page 1-----------------------";
alert( s.match(/[-]{23}[ ]*Page[ ]*[0-9]*[-]{23}/) != null);

匹配()函数返回匹配的字符串值或如果模式不以字符串相匹配。以上code显示真正

match() function returns the matched string value or null if pattern does not match with string. The above code show true

我的C code:

#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语句上面打印不匹配!我不知道如何解决这一问题。先谢谢了。

the if-statement above print NO match! I have no idea how to fix this. Thanks in advance.

推荐答案

有关正则表达式库来识别出全部的常规前pression,在使用REG_EXTENDED的 regcomp 标志。

For the regex library to recognize the full regular expression, use REG_EXTENDED in the regcomp flag.

可以使用

你的意思是捕获组?喜欢这个?

Do you mean capturing groups? Like this?

#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为什么regexec()不匹配此模式,但匹配()的JavaScript的作品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆