1

I would like to print the sub expression of match "bytes". I have simplified this example so I can debug other components of my code:

char *bytes="[[:print:]]*\(bytes\)";
regex_t compiled;
regmatch_t matches[2];
char currentLine[512];

fgets(currentLine, 512, ifile);
regcomp(&compiled, bytes, REG_EXTENDED);
if(regexec(&compiled, currentLine, 2, matches, 0)==0){
    printf("%s\n", bytes+matches[1].rm_so);
}

Where

currentLine= "Free Memory: 5062026704 bytes (79%)";'

takes place after the fgets.

The printed line I receive is an unformatted printf statement from another function - one which runs after this one. I have a few different ideas on where my problem might be(regex syntax, memory allocation, usage of regmatch_t), and I have been trying different combinations of solutions all morning but to no avail as of yet.

How can I correctly print the matched substring?

umphish
  • 75
  • 1
  • 9

1 Answers1

0

Different problem but using some of the sample code from here I modified this line:

char *bytes="[[:print:]]*\(bytes\)";
                         ^      ^

to this:

char *bytes="[[:print:]]*(bytes)";
                        ^ 

and modified the print statements as follows:

printf("0: [%.*s]\n", matches[0].rm_eo - matches[0].rm_so, currentLine + matches[0].rm_so);
printf("1: [%.*s]\n", matches[1].rm_eo - matches[1].rm_so, currentLine + matches[1].rm_so);

The format string you may not have seen before but this thread covers it well.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • You simply want to remove the backslashes, not replace the second one with an asterisk. As written now, it would match `byte` or `bytesssssssss`. (Hmm, it looks like the OP tried to write a Basic Regular Expression, forgot momentarily about C's string escapes, but compiled it as an Extended RE anyway.) – pilcrow Aug 09 '13 at 21:00