Skip to content

Instantly share code, notes, and snippets.

@oz123
Created December 1, 2014 08:34
Show Gist options
  • Save oz123/9bfc2a7266dd2ac28c56 to your computer and use it in GitHub Desktop.
Save oz123/9bfc2a7266dd2ac28c56 to your computer and use it in GitHub Desktop.
A reminder to self on how to use regex in c
#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(&regex, "{ $date : [[:digit:]]\\{3\\} }", 0);
if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }
/* Execute regular expression */
reti = regexec(&regex, 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, &regex, 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(&regex);
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