Skip to content

Instantly share code, notes, and snippets.

@andlrc
Created February 1, 2022 12:10
Show Gist options
  • Save andlrc/d87762391a67fd13c19646759094dbdd to your computer and use it in GitHub Desktop.
Save andlrc/d87762391a67fd13c19646759094dbdd to your computer and use it in GitHub Desktop.
#include <err.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
void redie(int eval, regex_t *re, char *msg) {
char buf[1024];
regerror(eval, re, buf, sizeof(buf));
errx(1, "%s: %s", msg, buf);
}
int main(int argc, char *argv[])
{
regex_t re;
regmatch_t match[10];
int eval;
char *str = argv[1] ? argv[1] : " hello";
eval = regcomp(&re, "^ *| *$", REG_EXTENDED);
if (eval) {
redie(eval, &re, "regcomp");
}
match[0].rm_so = 0;
match[0].rm_eo = strlen(str);
printf("--- [%lld,%lld] --- <%s>", match[0].rm_so, match[0].rm_eo, str);
eval = regexec(&re, str, 10, match, REG_STARTEND);
printf("--- %d [%lld,%lld]\n", eval, match[0].rm_so, match[0].rm_eo);
if (eval) {
redie(eval, &re, "regexec: 0");
}
match[0].rm_so = match[0].rm_eo;
match[0].rm_eo = strlen(str);
printf("--- [%lld,%lld] --- <%s>", match[0].rm_so, match[0].rm_eo, str);
eval = regexec(&re, str, 10, match, REG_NOTBOL | REG_STARTEND);
printf("--- %d [%lld,%lld]\n", eval, match[0].rm_so, match[0].rm_eo);
if (eval) {
redie(eval, &re, "regexec: 1");
}
regfree(&re);
return 0;
}
@andlrc
Copy link
Author

andlrc commented Feb 1, 2022

On macOS the above outputs:

$ ./pgm " hello"
---  [0,6] --- < hello>---  0 [0,1]
---  [1,6] --- < hello>---  1 [1,6]
pgm: regexec: 1: regexec() failed to match

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment