Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nnathan
Last active January 8, 2019 01:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nnathan/8a062b5a8831ff8aeb9b7d20af188dd3 to your computer and use it in GitHub Desktop.
Save nnathan/8a062b5a8831ff8aeb9b7d20af188dd3 to your computer and use it in GitHub Desktop.
regex alternation is not commutative
/* turns out this is wrong, the regex "quic | noise" contains spaces you need to consider */
/*
* $ ./r
* "quic | noise" matches "high pitched noise coming from car"
* $ ./r s
* "noise | quic" matches "a quick fix"
* "noise | quic" matches "high pitched noise coming from car"
*/
#include <stdio.h>
#include <regex.h>
int main(int argc, char **argv) {
char *p = "quic | noise";
char haystack[2][1024] = {
"a quick fix",
"high pitched noise coming from car",
};
char err[1024];
regex_t r;
int s;
if (argc > 1 && argv[1][0] == 's') {
p = "noise | quic";
}
s = regcomp(&r, p, REG_EXTENDED | REG_NEWLINE | REG_NOSUB | REG_ICASE);
if (s) {
regerror(s, &r, err, sizeof(err));
fprintf(stderr, "regex error: %s\n", err);
return 1;
}
for (int i = 0; i < sizeof(haystack)/sizeof(haystack[0]); i++) {
s = regexec(&r, haystack[i], 0, NULL, 0);
if (!s) {
printf("\"%s\" matches \"%s\"\n", p, haystack[i]);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment