Created
December 1, 2014 08:34
-
-
Save oz123/9bfc2a7266dd2ac28c56 to your computer and use it in GitHub Desktop.
A reminder to self on how to use regex in c
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
#include <regex.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int main(int argc, char *argv[]){ | |
regex_t regex; | |
int reti; | |
char msgbuf[100]; | |
size_t max_groups = 1; | |
regmatch_t groups[max_groups]; | |
/* Compile regular expression */ | |
reti = regcomp(®ex, "{ $date : [[:digit:]]\\{3\\} }", 0); | |
if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); } | |
/* Execute regular expression */ | |
reti = regexec(®ex, argv[1], max_groups, groups, 0); | |
if( !reti ){ | |
puts("Match"); | |
char m[groups[0].rm_eo - groups[0].rm_so + 1]; | |
puts("Allocated"); | |
m[groups[0].rm_eo] = 0; | |
strncpy(m, argv[1]+groups[0].rm_so, groups[0].rm_eo - groups[0].rm_so); | |
printf("%s \n", argv[1]+groups[0].rm_so); | |
printf("%s \n", m); | |
} | |
else if( reti == REG_NOMATCH ){ | |
puts("No match"); | |
} | |
else{ | |
regerror(reti, ®ex, msgbuf, sizeof(msgbuf)); | |
fprintf(stderr, "Regex match failed: %s\n", msgbuf); | |
exit(1); | |
} | |
/* Free compiled regular expression if you want to use the regex_t again */ | |
regfree(®ex); | |
return 0; | |
} | |
/* Regex example | |
* $ gcc test_regex.c | |
* $ ./a.out '{ $date : 123 }notreached' | |
Match | |
Allocated | |
{ $date : 123 }notreached | |
{ $date : 123 } | |
* | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment