我需要在c语言中提取两个字符串模式之间的文本。
例子:
aaaaaa<BBBB>TEXT TO EXTRACT</BBBB>aaaaaaaaa
PATTERN1=<BBBB>
PATTERN2=</BBBB>
谢谢。
最佳答案
这是一个活生生的例子
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *s = "aaaaaa<BBBB>TEXT TO EXTRACT</BBBB>aaaaaaaaa";
const char *PATTERN1 = "<BBBB>";
const char *PATTERN2 = "</BBBB>";
char *target = NULL;
char *start, *end;
if ( start = strstr( s, PATTERN1 ) )
{
start += strlen( PATTERN1 );
if ( end = strstr( start, PATTERN2 ) )
{
target = ( char * )malloc( end - start + 1 );
memcpy( target, start, end - start );
target[end - start] = '\0';
}
}
if ( target ) printf( "%s\n", target );
free( target );
return 0;
}
输出是
TEXT TO EXTRACT