Skip to content

Instantly share code, notes, and snippets.

@linyows
Created February 24, 2017 02:36
Show Gist options
  • Save linyows/dde12e07d27061dce79d0bbfb3d985d1 to your computer and use it in GitHub Desktop.
Save linyows/dde12e07d27061dce79d0bbfb3d985d1 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
#include <string.h>
// Unatched: 0
// Matched: 1
int octopass_match(char *str, char *pattern, char **matched)
{
int res;
regex_t re;
regmatch_t pm;
res = regcomp(&re, pattern, REG_EXTENDED);
if (res != 0) {
return 0;
}
int cnt = 0;
int offset = 0;
res = regexec(&re, &str[0], 1, &pm, REG_EXTENDED);
if (res != 0) {
return 0;
}
while (res == 0) {
int relative_start = pm.rm_so + 1;
int relative_end = pm.rm_eo - 1;
int absolute_start = offset + relative_start;
int absolute_end = offset + relative_end;
int i;
char *match_word;
match_word = calloc(128, sizeof(char *));
for (i = absolute_start; i < absolute_end; i++) {
char *tmp;
tmp = calloc(128, sizeof(char *));
sprintf(tmp, "%c", str[i]);
strcat(match_word, tmp);
}
matched[cnt] = strdup(match_word);
free(match_word);
offset += pm.rm_eo;
cnt++;
res = regexec(&re, &str[0] + offset, 1, &pm, 0);
}
return cnt;
}
int main(void)
{
char *str = "[ \"abc\", \"de\", \"F012\" ]\0";
char *pattern = "\"([A-z0-9_-]+)\"";
char **matched;
matched = calloc(128, sizeof(char *));
int res;
int cnt = octopass_match(str, pattern, matched);
if (cnt > 0) {
int i;
for (i = 0; i < cnt; i++) {
printf("%s\n", matched[i]);
}
free(matched);
}
return 0;
}
/*
int main(void)
{
int a;
regex_t re;
const char str[128] = "[ \"abc\", \"de\", \"F012\" ]\0";
char *pattern = "\"([A-z0-9_-]+)\"";
regmatch_t pm;
a = regcomp(&re, pattern, REG_EXTENDED);
if (a != 0) {
puts("invalid");
return 0;
}
int cnt = 0;
int offset = 0;
a = regexec(&re, &str[0], 1, &pm, REG_EXTENDED);
char **words;
words = malloc(128);
while (a == 0) {
int relative_start = pm.rm_so + 1;
int relative_end = pm.rm_eo - 1;
int absolute_start = offset + relative_start;
int absolute_end = offset + relative_end;
int i;
char *match_word;
match_word = malloc(128);
for (i = absolute_start; i < absolute_end; i++) {
char *tmp;
sprintf(tmp, "%c", str[i]);
strcat(match_word, tmp);
}
printf("match: %s\n", match_word);
free(match_word);
words[cnt] = strdup(match_word);
offset += pm.rm_eo;
cnt++;
a = regexec(&re, &str[0] + offset, 1, &pm, 0);
}
int ii;
for (ii = 0; ii < cnt; ii++) {
printf("%s\n", words[ii]);
}
return 0;
} */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment