代码:
#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( ®ex, ".*\\W(\\w+_Init)\\W*", 0 );
if( errCode ) {
char errMsg[1024];
regerror( errCode, ®ex, errMsg, sizeof( errMsg ));
fprintf( stderr, "%s\n", errMsg );
return 1;
}
for( i = 0U; i < sizeof(nmLines)/sizeof(nmLines[0]); ++i ) {
errCode =
regexec(
®ex,
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( ®ex );
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( ®ex, ".*\\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/