So im just starting to pick up c my end goal is to write a function that searches a string with a regular expression and returns an array of matches.
The biggest problem I'm having is saving the strings into memory that can be return or referenced to in a pointer passed in as a parameter.
I'd really like a way to tell how many matches there are so i could do something like the c# equivalent; if(matches.Count() > 0) { /* we have a match! */ }
Then get the resulting string of each match group depending on the pattern that I'll eventually pass in.
I know this isn't correct and probably has some other errors in practice but here is the code I walked away from trying to figure it out reading up on pointers, structs, char arrays..etc
typedef struct
{
char *match;
} Matches;
int main()
{
regex_t regex;
int reti;
char msgbuf[100];
int max_matches = 10;
regmatch_t m[max_matches];
char str[] = "hello world";
reti = regcomp(®ex, "(hello) (world)", REG_EXTENDED);
if( reti )
{
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
reti = regexec(®ex, str, (size_t) max_matches, m, 0);
if( !reti )
{
puts("Match");
}
else if( reti == REG_NOMATCH )
{
puts("No match");
}
else
{
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
char *p = str;
int num_of_matches = 0;
Matches *matches;
int i = 0;
for(i = 0; i < max_matches; i++)
{
if (m[i].rm_so == -1) break;
int start = m[i].rm_so + (p - str);
int finish = m[i].rm_eo + (p - str);
if (i == 0)
printf ("$& is ");
else
printf ("$%d is ", i);
char match[finish - start + 1];
memcpy(match, str + start, finish - start);
match[sizeof(match)] = 0;
matches[i].match = match; //Need to get access to this string in an array outside of the loop
printf ("'%.*s' (bytes %d:%d)\n", (finish - start), str + start, start, finish);
num_of_matches++;
}
p += m[0].rm_eo;
for(i = 0; i < num_of_matches; i++)
{
printf("'%s'\n", matches[i].match);
}
/* Free compiled regular expression if you want to use the regex_t again */
regfree(®ex);
return 0;
}
just when i thought i got it when only matching "world" i noticed when i commented out the printf statements the last printf statement was returning empty chars or random chars.