-
-
Save nnathan/8a062b5a8831ff8aeb9b7d20af188dd3 to your computer and use it in GitHub Desktop.
regex alternation is not commutative
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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