#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
#include <string.h>
// Function to find and return all content within curly braces
char** findCurlyBracesContent(const char* text, int* resultCount) {
const char* pattern = "\\{([^}]+)\\}";
regex_t regex;
regmatch_t matches[2];
char** results = NULL; // Dynamic array to store results
*resultCount = 0; // Initialize result count
int start = 0;
// Compile the regular expression
if (regcomp(®ex, pattern, REG_EXTENDED) != 0) {
fprintf(stderr, "Could not compile regex\n");
return NULL;
}
// Search the input string for matches
while (start < strlen(text) &&
regexec(®ex, text + start, 2, matches, 0) == 0) {
// Get start and end positions of the match
int match_start = matches[1].rm_so + start; // Capturing group 1 start
int match_end = matches[1].rm_eo + start; // Capturing group 1 end
int length = match_end - match_start;
// Allocate memory for the new match
char* match = (char*)malloc((length + 1) * sizeof(char));
strncpy(match, text + match_start, length);
match[length] = '\0';
// Expand the results array and store the match
results = (char**)realloc(results, (*resultCount + 1) * sizeof(char*));
results[*resultCount] = match;
(*resultCount)++;
// Move the search start to the end of the current match
start += matches[0].rm_eo;
}
// Free the compiled regex
regfree(®ex);
return results;
}
// Function to free memory allocated for the results
void freeResults(char** results, int count) {
for (int i = 0; i < count; i++) {
free(results[i]);
}
free(results);
}
int main() {
const char* text = "This is a {string} with {words} in curly {brackets}";
int resultCount = 0;
char** results = findCurlyBracesContent(text, &resultCount);
for (int i = 0; i < resultCount; i++) {
printf("Found: %s\n", results[i]);
}
freeResults(results, resultCount);
return 0;
}
/*
run:
Found: string
Found: words
Found: brackets
*/