45 lines
1.0 KiB
C
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(®ex, pattern, REG_EXTENDED);
|
|
if (ret != 0) {
|
|
char error_message[100];
|
|
regerror(ret, ®ex, error_message, sizeof(error_message));
|
|
printf("Regex compilation error: %s\n", error_message);
|
|
return;
|
|
}
|
|
|
|
while (1) {
|
|
ret = regexec(®ex, 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(®ex);
|
|
}
|
|
|
|
int main() {
|
|
const char *text = "abc123xyz456";
|
|
extract_numbers(text);
|
|
|
|
return 0;
|
|
}
|