This is not "standard", but if you are using GCC and glibc, you can use regular expressions in C:
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>
int getUrlName( char **name, char *url )
{
static char regex[] = "^.+://([^/]+)/.*$";
regex_t rex;
regmatch_t rm[2]; // expected 2 matches:
// the main one and the group.
// Compile extended posix regex (ignore case).
if ( regcomp( &rex, regex, REG_EXTENDED | REG_ICASE ) )
return 0;
// Collect matches.
if ( regexec( &rex, url, 2, rm, 0 ) )
{
regfree( &rex );
return 0;
}
// Don't need rex anymore.
regfree( &rex );
// if the group has a match...
if ( rm[1].rm_so >= 0 )
{
// allocate space for substring,
// copy the match and returns with success.
char *p;
size_t chars = rm[1].rm_eo - rm[1].rm_so;
p = malloc( sizeof(char) * chars + 1 );
memcpy( p, url + rm[1].rm_so, chars );
p[chars] = '\0';
*name = p;
return 1;
}
return 0;
}
int main( void )
{
char s[] = "http://example.com/index.html";
char *p;
if ( ! getUrlName( &p, s ) )
{
fputs( "Cannot find a match.\n", stderr );
return EXIT_FAILURE;
}
printf( "Match: \"%s\".\n", p );
free( p );
return EXIT_SUCCESS;
}