这是我的Python程序:
import re
print re.findall( "([se]{2,30})ting", "testingtested" )
其输出为:
^{pr2}$这正是我所期待的。我希望返回“es”,因为我搜索了2-30个字符“e”或“s”,后面跟着“ting”。在
这是我的C程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>
int main(void) {
regex_t preg;
regmatch_t pmatch;
char string[] = "testingtested";
//Compile the regular expression
if ( regcomp( &preg, "([se]{2,30})ting", REG_EXTENDED ) ) {
printf( "ERROR!\n" );
return -1;
} else {
printf( "Compiled\n" );
}
//Do the search
if ( regexec( &preg, string, 1, &pmatch, REG_NOTEOL ) ) {
printf( "No Match\n" );
} else {
//Allocate memory on the stack for this
char substring[pmatch.rm_eo - pmatch.rm_so + 1];
//Copy the substring over
printf( "%d %d\n", pmatch.rm_so, pmatch.rm_eo );
strncpy( substring, &string[pmatch.rm_so], pmatch.rm_eo - pmatch.rm_so );
//Make sure there's a null byte
substring[pmatch.rm_eo - pmatch.rm_so] = 0;
//Print it out
printf( "Match\n" );
printf( "\"%s\"\n", substring );
}
//Release the regular expression
regfree( &preg );
return EXIT_SUCCESS;
}
它的输出是:
Compiled
1 7
Match
"esting"
为什么C程序会在结果中包含“ting”?我有没有办法排除“婷”的部分?在
虽然正则表达式“在任何地方都或多或少相同”,但具体支持的功能因实现而异。在
不幸的是,在设计正则表达式时,需要分别查阅每个regex库的文档。在
pmatch
是整个匹配项,而不是第一个带圆括号的子表达式。在尝试将
pmatch
更改为2个元素的数组,然后将2传递给regexec
,并使用[1]
元素来获得子表达式匹配。在对于其他引用了C和Python之间的差异以及不同类型正则表达式的人来说,这些都是不相关的。这个表达式很简单,这是行不通的。在
相关问题 更多 >
编程相关推荐