Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a string that is present between two brackets?

Tags:

c++

c

For example if the string is:

XYZ ::[1][20 BB EC 45 40 C8 97 20 84 8B 10]

The output should be:

20 BB EC 45 40 C8 97 20 84 8B 10

int main()
{
    char input = "XYZ ::[1][20 BB EC 45 40 C8 97 20 84 8B 10]";
    char output[500];
    // what to write here so that i can get the desired output as: 
    // output = "20 BB EC 45 40 C8 97 20 84 8B 10"
    return 0;
}
like image 327
Jatin Avatar asked Nov 18 '25 01:11

Jatin


2 Answers

In C, you could do this with a scanset conversion (though it's a bit RE-like, so the syntax gets a bit strange):

sscanf(input, "[%*[^]]][%[^]]]", second_string);

In case you're wondering how that works, the first [ matches an open bracket literally. Then you have a scanset, which looks like %[allowed_chars] or %[^not_allowed_chars]. In this case, you're scanning up to the first ], so it's %[^]]. In the first one, we have a * between the % and the rest of the conversion specification, which means sscanf will try to match that pattern, but ignore it -- not assign the result to anything. That's followed by a ] that gets matched literally.

Then we repeat essentially the same thing over again, but without the *, so the second data that's matched by this conversion gets assigned to second_string.

With the typo fixed and a bit of extra code added to skip over the initial XYZ ::, working (tested) code looks like this:

#include <stdio.h>

int main() { 
    char *input = "XYZ ::[1][20 BB EC 45 40 C8 97 20 84 8B 10]";

    char second_string[64];
    sscanf(input, "%*[^[][%*[^]]][%[^]]]", second_string);

    printf("content: %s\n", second_string);
    return 0;
}
like image 110
Jerry Coffin Avatar answered Nov 20 '25 17:11

Jerry Coffin


Just find the second [ and start extracting (or just printing) until next ]....

like image 36
Dante May Code Avatar answered Nov 20 '25 17:11

Dante May Code



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!