FWIW, here's an example using the GNU regex library (which you may or may not have available, depending on your platform). It's probably overkill for what you're trying to do, but it's an alternative to the methods the other people have shown you. Depending on the complexity of the pattern you're trying to match, it can come in handy.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <regex.h>
int main( void )
{
/**
* Text we want to search.
*/
const char *text = "Svnsv am /apple/ rv dbndkbrb am /orange/ rv dbundib am /bestfruit/ rv drbrnboie am /watermelon/ rv";
/**
* The following pattern will isolate the strings between the '/'
* characters. ".*" matches any sequence of characters, so basically
* the pattern reads, "skip over any characters until we see an opening
* '/', then match everything up to the next '/', then repeat 3 more
* times".
*/
const char *ptn = ".*/(.*)/.*/(.*)/.*/(.*)/.*/(.*)/.*";
/**
* Regular expression type.
*/
regex_t regex;
/**
* Compile the regular expression
*/
if ( regcomp(®ex, ptn, REG_EXTENDED) != 0 )
{
fprintf( stderr, "regcomp failed on %s\n", ptn );
exit( 0 );
}
/**
* Set up an array to store the start and end positions of the
* matched substrings within text.
*/
fprintf( stdout, "Number of subexpressions: %zu\n", regex.re_nsub );
size_t matchCount = regex.re_nsub + 1;
regmatch_t pmatch[matchCount];
int ret;
/**
* Execute the regular expression, then print out the matched expressions
*/
if ( ( ret = regexec( ®ex, text, matchCount, pmatch, 0)) != 0 )
{
fprintf( stderr, "%s does not match %s, return code %d\n", text, ptn, ret );
}
else
{
fprintf( stdout, "Sucessful match\n" );
for ( size_t i = 0; i < matchCount; i++ )
{
if ( pmatch[i].rm_so >= 0 )
{
fprintf( stdout, "match %zu (start: %3lu; end: %3lu): %*.*s\n", i,
(unsigned long) pmatch[i].rm_so,
(unsigned long) pmatch[i].rm_eo,
(int) ( pmatch[i].rm_eo - pmatch[i].rm_so ),
(int) ( pmatch[i].rm_eo - pmatch[i].rm_so ),
text + pmatch[i].rm_so );
}
}
}
return 0;
}
And here's the output:
Number of subexpressions: 4
Sucessful match
match 0 (start: 0; end: 98): Svnsv am /apple/ rv dbndkbrb am /orange/ rv dbundib am /bestfruit/ rv drbrnboie am /watermelon/ rv
match 1 (start: 10; end: 15): apple
match 2 (start: 33; end: 39): orange
match 3 (start: 56; end: 65): bestfruit
match 4 (start: 84; end: 94): watermelon
If you want to copy the matched strings, you'll need to use strncpy
and make sure you terminate the string properly:
char matched_string[MAX_STRING_LENGTH + 1] = {0};
...
size_t length = pmatch[1].rm_eo - pmatch[1].rm_so;
strncpy( matched_string, text + pmatch[1].rm_so, length );
/**
* Make sure string is 0 terminated
*/
matched_string[ length ] = 0;