How to find text between two strings in c

Fco. Javier Martínez  Conesa picture Fco. Javier Martínez Conesa · Jul 11, 2014 · Viewed 11.8k times · Source

I need to extract the text between 2 string patterns in c.

Example:

aaaaaa<BBBB>TEXT TO EXTRACT</BBBB>aaaaaaaaa

PATTERN1=<BBBB>
PATTERN2=</BBBB>

Thanks.

Answer

Vlad from Moscow picture Vlad from Moscow · Jul 11, 2014

Here is an alive example of how to do this

#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;
}

The output is

TEXT TO EXTRACT