c - C 中的正则表达式在 egrep 匹配时不匹配

标签 c regex

代码:

#include <regex.h>
#include <stdio.h>

int main() {
   unsigned   i;
   regex_t    regex;
   regmatch_t captures[2];
   char *     nmLines[] = {
      "0000000000000a10 t frame_dummy",
      "0000000000000a40 T geom_Init",
      "0000000000000b30 t geom_RectangleAllocate",
   };
   int errCode = regcomp( &regex, ".*\\W(\\w+_Init)\\W*", 0 );
   if( errCode ) {
      char errMsg[1024];
      regerror( errCode, &regex, errMsg, sizeof( errMsg ));
      fprintf( stderr, "%s\n", errMsg );
      return 1;
   }
   for( i = 0U; i < sizeof(nmLines)/sizeof(nmLines[0]); ++i ) {
      errCode =
         regexec(
            &regex,
            nmLines[i],
            sizeof(captures)/sizeof(captures[0]),
            captures,
            0 );
      if( 0 == errCode ) {
         printf( "Match : %s, between %d and %d\n",
            nmLines[i], captures[1].rm_so, captures[1].rm_eo );
      }
      else {
         printf( "Doesn't match : %s\n", nmLines[i] );
      }
   }
   regfree( &regex );
   return 0;
}

输出:

$ gcc -W -Wall -o rx rx.c ; ./rx
Doesn't match : 0000000000000a10 t frame_dummy
Doesn't match : 0000000000000a40 T geom_Init
Doesn't match : 0000000000000b30 t geom_RectangleAllocate

使用 egrep 过滤的相同输出匹配 3 之间的一行(右边那一行):

$ ./rx | egrep '.*\W(\w+_Init)\W*'
Doesn't match : 0000000000000a40 T geom_Init
$ 

为什么 regexec 失败而 egrep 使用相同的表达式成功?

最佳答案

我的错误已修复!

我使用的表达式是POSIX 扩展正则表达式,而不是POSIX 基本正则表达式

修改后的代码是:

int errCode = regcomp( &regex, ".*\\W(\\w+_Init)\\W*", REG_EXTENDED );

Here is an extract of the documentation:

  • REG_EXTENDED:在解释正则表达式时使用 POSIX 扩展正则表达式 (ERE) 语法。如果未设置,则使用 POSIX 基本正则表达式 (BRE) 语法。

regcomp 不报告错误,因为表达式在 BRE 中有效,但没有意义,因为 \W 不作为单词边界和 \w 作为单词部分。这些字符按原样处理。

Here is another helpful documentation关于 ERE 的 GNU 扩展,例如 \W\w

关于c - C 中的正则表达式在 egrep 匹配时不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21589811/

相关文章:

C Puzzle - 玩类型

c - FLOPS Intel 内核并使用 C(内积)对其进行测试

Java正则表达式(贪婪/非贪婪)

python - 正则表达式选择逗号和句点 Python

php - PHP preg_replace 中的\w 仅覆盖 UTF-8 字符的第二个字节

c - 在 C 中发送字符串时,UNIX 中的未命名管道子消息不会被父亲接收到

c - 根据 If 制作宏

c - STM32发现F3 SPI环回RXFIFO没有接收到数据

java - 分割字符串,同时保留除转义分隔符之外的分隔符(正则表达式)

c# - 控制平衡括号