2024-12-09 16:06:47 +08:00

45 lines
1.0 KiB
C

#include <stdio.h>
#include <regex.h>
#define MAX_MATCHES 10
void extract_numbers(const char *text) {
regex_t regex;
regmatch_t matches[MAX_MATCHES];
const char *pattern = "[0-9]+";
int ret;
ret = regcomp(&regex, pattern, REG_EXTENDED);
if (ret != 0) {
char error_message[100];
regerror(ret, &regex, error_message, sizeof(error_message));
printf("Regex compilation error: %s\n", error_message);
return;
}
while (1) {
ret = regexec(&regex, text, MAX_MATCHES, matches, 0);
if (ret != 0) {
break;
}
for (int i = 0; i < MAX_MATCHES && matches[i].rm_so != -1; i++) {
int start = matches[i].rm_so;
int end = matches[i].rm_eo;
printf("Match found: %.*s\n", end - start, text + start);
}
printf("%s\n", text);
text += matches[0].rm_eo;
}
regfree(&regex);
}
int main() {
const char *text = "abc123xyz456";
extract_numbers(text);
return 0;
}