Last active
January 27, 2021 08:37
-
-
Save yashi/2e9a9ec634cc12e572b99a875edc232e to your computer and use it in GitHub Desktop.
PCRE Regex
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
/* -*- compile-command: "gcc -Wall -Wextra -g $(pkg-config --cflags --libs libpcre2-8) pcre.c" -*- */ | |
#define PCRE2_CODE_UNIT_WIDTH 8 | |
#include <pcre2.h> | |
#include <string.h> | |
#include <stdio.h> | |
int main(void) | |
{ | |
pcre2_code *re; | |
PCRE2_SPTR pattern = (PCRE2_SPTR)"^b"; | |
pcre2_match_data *match_data; | |
int errornumber; | |
PCRE2_SIZE erroroffset; | |
int ret; | |
size_t i; | |
char *strings[] = { | |
"foo", | |
"bar", | |
"baz", | |
}; | |
re = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, 0, &errornumber, &erroroffset, NULL); | |
if (!re) { | |
PCRE2_UCHAR buffer[256]; | |
pcre2_get_error_message(errornumber, buffer, sizeof(buffer)); | |
printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset, | |
buffer); | |
return 1; | |
} | |
match_data = pcre2_match_data_create_from_pattern(re, NULL); | |
for (i=0; i<(sizeof(strings)/sizeof(strings[0])); i++) { | |
ret = pcre2_match(re, (PCRE2_SPTR)strings[i], strlen(strings[i]), 0, 0, match_data, NULL); | |
if (ret < 0) { | |
switch(ret) { | |
case PCRE2_ERROR_NOMATCH: | |
printf("pattern `%s' does not match: %s\n", pattern, strings[i]); | |
break; | |
default: | |
printf("Matching error %d\n", ret); | |
break; | |
} | |
} | |
else { | |
printf("pattern `%s' match: %s\n", pattern, strings[i]); | |
} | |
} | |
pcre2_match_data_free(match_data); | |
pcre2_code_free(re); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment