In project C, I wrote a function to return the first capture group to a regular expression search.
What I expect to achieve is best described by the release of this online parser (note the output of the capture group in the right pane).
The function and test code I wrote are as follows:
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
#include <string.h>
#include <assert.h>
typedef int bool;
#define true 1
#define false 0
bool get_first_match(const char* search_str, const char* reg_exp, char** output)
{
int res, len;
regex_t preg;
regmatch_t pmatch;
if( (res = regcomp(&preg, reg_exp, REG_EXTENDED)) != 0)
{
char* error = (char*)malloc(1024*sizeof(char));
regerror(res, &preg, error, 1024);
output = &error;
return false;
}
res = regexec(&preg, search_str, 1, &pmatch, REG_NOTBOL);
if(res == REG_NOMATCH)
{
return true;
}
len = pmatch.rm_eo - pmatch.rm_so;
char* result = (char*)malloc( (len + 1) * sizeof(char) );
memcpy(result, search_str + pmatch.rm_so, len);
result[len] = 0;
*output = result;
regfree(&preg);
return true;
}
int main()
{
const char* search_str = "param1=blah¶m2=blahblah¶m3=blahetc&map=/usr/bin/blah.map";
const char* regexp = "map=([^\\&]*)(&|$)";
char* output;
bool status = get_first_match(search_str, regexp, &output);
if(status){
if(output)
printf("Found match: %s\n", output);
else
printf("No match found.");
}
else{
printf("Regex error: %s\n", output);
}
free(output);
return 0;
}
However, the output that I get from the C code contains part of the map=
line in it, although I clearly excluded this in my first capture group.
What can I do to get a capture group without a part map=
? Why do I get different results from an online analyzer compared to my C program?