#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
int main() {
const char* str = "The price is 148.95 dollars";
const char* pattern = "[-+]?[0-9]*\\.?[0-9]+";
regex_t regex;
regmatch_t match[1];
if (regcomp(®ex, pattern, REG_EXTENDED) != 0) {
fprintf(stderr, "Failed to compile regex\n");
return 1;
}
if (regexec(®ex, str, 1, match, 0) == 0) {
char extracted[64];
int length = match[0].rm_eo - match[0].rm_so;
strncpy(extracted, str + match[0].rm_so, length);
extracted[length] = '\0';
float number = atof(extracted);
printf("Extracted float: %.2f\n", number);
}
regfree(®ex);
return 0;
}
/*
run:
Extracted float: 148.95
*/