16,472
社区成员
发帖
与我相关
我的任务
分享
//摘自《代码之美》
// 字符 含义
// . 匹配任意的单个字符
// ^ 匹配输入字符串的开头
// $ 匹配输入字符串的结尾
// * 匹配前一个字符的零个或者多个出现
#include <stdio.h>
int matchhere(char *regexp, char *text);
int matchstar(int c, char *regexp, char *text) {// matchstar: search for c*regexp at beginning of text
do {// a * matches zero or more instances
if (matchhere(regexp, text)) return 1;
} while (*text != '\0' && (*text++ == c || c == '.'));
return 0;
}
int matchhere(char *regexp, char *text) {// matchhere: search for regexp at beginning of text
if (regexp[0] == '\0') return 1;
if (regexp[1] == '*') return matchstar(regexp[0], regexp+2, text);
if (regexp[0] == '$' && regexp[1] == '\0') return *text == '\0';
if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text)) return matchhere(regexp+1, text+1);
return 0;
}
int match(char *regexp, char *text) {// match: search for regexp anywhere in text
if (regexp[0] == '^') return matchhere(regexp+1, text);
do {// must look even if string is empty
if (matchhere(regexp, text)) return 1;
} while (*text++ != '\0');
return 0;
}
void main() {
printf("%d==match(abc ,abc)\n",match("abc" ,"abc"));
printf("%d==match(^a ,abc)\n",match("^a" ,"abc"));
printf("%d==match(c$ ,abc)\n",match("c$" ,"abc"));
printf("%d==match(a.c ,abc)\n",match("a.c" ,"abc"));
printf("%d==match(a.*c,abc)\n",match("a.*c","abc"));
printf("-------------------\n");
printf("%d==match(ABC ,abc)\n",match("ABC" ,"abc"));
printf("%d==match(^B ,abc)\n",match("^B" ,"abc"));
printf("%d==match(A$ ,abc)\n",match("A$" ,"abc"));
printf("%d==match(a..c,abc)\n",match("a..c","abc"));
printf("%d==match(a.*d,abc)\n",match("a.*d","abc"));
}
//1==match(abc ,abc)
//1==match(^a ,abc)
//1==match(c$ ,abc)
//1==match(a.c ,abc)
//1==match(a.*c,abc)
//-------------------
//0==match(ABC ,abc)
//0==match(^B ,abc)
//0==match(A$ ,abc)
//0==match(a..c,abc)
//0==match(a.*d,abc)
#include "stdafx.h"
#include "memory.h"
#include "string.h"
int main(int argc, char* argv[])
{
char ori[] = "abcdab1234";
char format[] = "%sab%s34%s";
char *p = format;
char tmp[ 20 ][ 20 ];
int count;
int len;
int i;
memset( tmp, 0, sizeof( tmp ) );
count = 0;
len = 0;
while( *p )
{
if( '%' == *p )
{
if( p != format )
{
count++;
}
len = 0;
tmp[ count ][ len++ ] = '%';
p++;
tmp[ count ][ len++ ] = *p;
len = 0;
if( *p )
{
count++;
}
}
else
{
tmp[ count ][ len++ ] = *p;
}
p++;
}
count++;
for( i = 0; i < count; i++ )
{
printf( "format part %d is --- %s \r\n", i + 1, tmp[ i ] );
}
char *q = ori;
for( i = 0; i < count; i++ )
{
if( !strcmp( tmp[ i ], "%s" ) )
{
char *t = strstr( q + 1, tmp[ i + 1 ] );
char dest[ 0x10 ] = "";
memcpy( dest, q, ( int )( t - q ) );
printf( "the %%s is %s \r\n", dest );
q += strlen( dest );
q += strlen( tmp[ i + 1 ] );
}
}
return 0;
}