Skip to content

Instantly share code, notes, and snippets.

@webstory
Last active June 7, 2018 04:19
Show Gist options
  • Save webstory/7c7a47600b2443fb40e2e92662d27c2f to your computer and use it in GitHub Desktop.
Save webstory/7c7a47600b2443fb40e2e92662d27c2f to your computer and use it in GitHub Desktop.
C regex for ini parse
#include <stdio.h>
#include <regex.h>
#include <string.h>
void getIni(char *result, const char *iniStr, const char *name) {
regex_t re;
char pattern[128];
regmatch_t groups[2];
sprintf(pattern, "\\s*%s\\s*=\\s*([^\r\n]+)", name);
regcomp(&re, pattern, REG_EXTENDED);
if(regexec(&re, iniStr, 2, groups, 0) == 0) {
// Matched
int sPos = groups[1].rm_so;
int len = groups[1].rm_eo - sPos;
while(*(iniStr + sPos + len - 1) == ' ') {
len--;
}
strncpy(result, iniStr + sPos, len);
result[len] = '\0';
} else {
result[0] = '\0';
}
regfree(&re);
}
int main(void) {
char result[100];
getIni(result, "hello = world \nyou=are so beautiful", "hello");
printf("%s: [%s]\n", "hello", result);
getIni(result, "hello = world \nyou=are so beautiful", "you");
printf("%s: [%s]\n", "you", result);
//printf("Hello World\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment