regular expressions in C match and print

前端 未结 1 1368
别跟我提以往
别跟我提以往 2021-01-28 22:31

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 {}

相关标签:
1条回答
  • 2021-01-28 22:55

    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;
    }
    
    0 讨论(0)
提交回复
热议问题