Vladimir Djukic
Vladimir Djukic

Reputation: 2072

regular expressions in C match and print

I have lines from file like this:

{123}   {12.3.2015 moday}    {THIS IS A TEST}

is It possible to get every value between brackets {} and insert into array?

Also I wold like to know if there is some other solution for this problem...

to get like this:

array( 123,
      '12.3.2015 moday',
      'THIS IS A TEST'
     )

My try:

  int r;
  regex_t reg;
  regmatch_t match[2];
  char *line = "{123}   {12.3.2015 moday}    {THIS IS A TEST}";

  regcomp(&reg, "[{](.*?)*[}]", REG_ICASE | REG_EXTENDED);

  r = regexec(&reg, line, 2, match, 0);
  if (r == 0) {
    printf("Match!\n");
    printf("0: [%.*s]\n", match[0].rm_eo - match[0].rm_so, line + match[0].rm_so);
    printf("1: %.*s\n", match[1].rm_eo - match[1].rm_so, line + match[1].rm_so);
  } else {
    printf("NO match!\n");
  }

This will result:

123}   {12.3.2015 moday}    {THIS IS A TEST

Anyone know how to improve this?

Upvotes: 0

Views: 1087

Answers (1)

nowox
nowox

Reputation: 29116

To help you you can use the regex101 website which is really useful.

Then I suggest you to use this regex:

/(?<=\{).*?(?=\})/g

Or any of these ones:

/\{\K.*?(?=\})/g
/\{\K[^\}]+/g
/\{(.*?)\}/g

Also available here for the first one:

https://regex101.com/r/bB6sE8/1

In C you could start with this which is an example for here:

#include <stdio.h>
#include <string.h>
#include <regex.h>

int main ()
{
    char * source = "{123}   {12.3.2015 moday}    {THIS IS A TEST}";
    char * regexString = "{([^}]*)}";
    size_t maxGroups = 10;

    regex_t regexCompiled;
    regmatch_t groupArray[10];
    unsigned int m;
    char * cursor;

    if (regcomp(&regexCompiled, regexString, REG_EXTENDED))
    {
        printf("Could not compile regular expression.\n");
        return 1;
    };

    cursor = source;
    while (!regexec(&regexCompiled, cursor, 10, groupArray, 0))
    {
        unsigned int offset = 0;

        if (groupArray[1].rm_so == -1)
            break;  // No more groups

        offset = groupArray[1].rm_eo;
        char cursorCopy[strlen(cursor) + 1];
        strcpy(cursorCopy, cursor);
        cursorCopy[groupArray[1].rm_eo] = 0;
        printf("%s\n", cursorCopy + groupArray[1].rm_so);
        cursor += offset;
    }
    regfree(&regexCompiled);
    return 0;
}

Upvotes: 2

Related Questions