#simple parser, lexer in C for cli arguments

3 messages · Page 1 of 1 (latest)

raw leafBOT
#

When your question is answered use !solved or the button below to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

little crag
#

Barring the use of a regular expression library, use repeated attempts at sscanf()...

#include <stdio.h>

int main()
{
    //const char* param = "5,4=10mV";
    //const char* param = "5-4=10mV";
    const char* param= "1-4,5=12mV,10mv";

    int r1_low;
    int r1_high;
    int r1_vref;

    int r2;
    int r2_vref;

    if (sscanf(param, "%d,%d=%dmV", &r1_low, &r1_high, &r1_vref) == 3)
    {
        printf("r1: %d-%d / %d mV\n", r1_low, r1_high, r1_vref);
    }
    else if (sscanf(param, "%d-%d=%dmv", &r1_low, &r1_high, &r1_vref) == 3)
    {
        printf("r1: %d-%d / %d mV\n", r1_low, r1_high, r1_vref);
    }
    else if (sscanf(param, "%d-%d,%d=%dmV,%dmv", &r1_low, &r1_high, &r2, &r1_vref, &r2_vref) == 5)
    {
        printf("r1: %d-%d / %d mV\n", r1_low, r1_high, r1_vref);
        printf("r2: %d / %d mV\n", r2, r2_vref);
    }
    // else if (sscanf(...) == 3) {}
}

Have a play here: https://godbolt.org/z/z3dM1nxdo

little crag
#

Keep in mind that the order in which you attempt to scan the string may be crucial.
You may find that some scan formats suit strings that shouldn't.
So find the right order.

Generally, start with the ones capturing the largest amount of variables.
(which is something my example does wrong - lol)