#include
static const char *const str =
"1) John Driverhacker;\n2) John Doe;\n3) John Foo;\n";
static const char *const re = "John.*o";
int main(void)
{
static const char *s = str;
regex_t regex;
regmatch_t pmatch[1];
regoff_t off, len;
if (regcomp(®ex, re, REG_NEWLINE))
exit(EXIT_FAILURE);
printf("Matches:\n");
for (int i = 0; ; i++) {
if (regexec(®ex, s, ARRAY_SIZE(pmatch), pmatch, 0))
break;
off = pmatch[0].rm_so + (s - str);
len = pmatch[0].rm_eo - pmatch[0].rm_so;
printf("#%d:\n", i);
printf("offset = %jd; length = %jd\n", (intmax_t) off,
(intmax_t) len);
printf("substring = \"%.*s\"\n", len, s + pmatch[0].rm_so);
s += pmatch[0].rm_eo;
}
}
$ ./example
Matches:
#0:
offset = 25; length = 7
substring = "John Do"
#1:
offset = 38; length = 8
substring = "John Foo"
typedef struct {
regoff_t rm_so;
regoff_t rm_eo;
} regmatch_t;
https://github.com/kokke/tiny-regex-c
#include "re.h"
int main(void)
{
/* Standard int to hold length of match */
int match_length;
/* Standard null-terminated C-string to search: */
const char* string_to_search = "ahem.. 'hello world !' ..";
/* Compile a simple regular expression using character classes, meta-char and greedy + non-greedy quantifiers: */
re_t pattern = re_compile("[Hh]ello [Ww]orld\\s*[!]?");
/* Check if the regex matches the text: */
int match_idx = re_matchp(pattern, string_to_search, &match_length);
if (match_idx != -1) {
printf("match: %s\n", string_to_search + match_idx);
}
}
match: hello world !' ..
END
→点关注,不迷路←