- 论坛徽章:
- 0
|
strstr()如何嵌套使用?
换一个regex的方法:
#include <stdio.h>;
#include <errno.h>;
#include <sys/types.h>;
#include <regex.h>;
/*
* position to string
*/
int RSTART; /* start offset to string */
int RLENGTH; /* substring length */
/*
* match匹配成功 , 返回 1
* 不能匹配 , 返回 0
*/
int match(char *string, char *pattern )
{
int status;
int errnum;
regex_t re;
status = errnum = 0;
bzero( &re , sizeof( regex_t ));
/*
* REG_EXTENDED 支持扩展的正则表达式
*/
if (( errnum = regcomp( &re, pattern, REG_EXTENDED )) != 0)
return(0) ;/* report error */
#ifdef DEBUG
fprintf(stderr, "re.re_nsub %d\n",re.re_nsub );
#endif
{
size_t nmatch = 1;
regmatch_t pmatch;
char *substring = string;
char *matchstr = NULL;
static int initial;
do
{
switch( status = regexec( &re, substring,
(size_t) nmatch, &pmatch, REG_NOTBOL ))
{
case 0:
initial = 1;
RSTART = substring - string + pmatch.rm_so ;
RLENGTH = pmatch.rm_eo - pmatch.rm_so;
matchstr = ( char * )calloc ( RLENGTH, sizeof( char ));
memcpy( matchstr , string + RSTART , RLENGTH );
fprintf( stdout, "\tmatchstr:%s,\t\tRSTART:%d,\tRLENGTH:%d ;\n",
matchstr, RSTART, RLENGTH );
free( matchstr );
matchstr = NULL;
substring += pmatch.rm_eo;
break;
case REG_NOMATCH:
if( initial == 0 )
fprintf( stderr, "not match !\n" );
else
{
fprintf( stderr, "\nmatch complete .\n" );
return 1;
}
break;
default:
fprintf( stderr,
"error, return value of regexec is: %d !.\n",status );
}
}
while( status == 0 );
}
regfree(&re);
if (status != 0)
return(0) ; /* report error */
return(1);
}
int main()
{
int retval = 0;
char *str="01234567890123456789012345678901";
fprintf( stdout, "str is [%s]\n", str );
retval = match( str, "901"
if( retval == 1 )
fprintf( stdout, "match ok!\n" );
else if( retval == 0 )
fprintf( stdout, "match fail!\n" );
return 0;
}
结果:
str is [01234567890123456789012345678901]
matchstr:901, RSTART:9, RLENGTH:3 ;
matchstr:901, RSTART:19, RLENGTH:3 ;
matchstr:901, RSTART:29, RLENGTH:3 ;
match complete .
match ok! |
|