[Solved] How to handle regular expression?


My main question is, are you using C or C++ ? The outcome and the appropriate/expected answer will be given with the right information.

As you are talking about C++ also, I will put a sample code to manage this using the library provided in C++ (since C++11 onwards).
Be warned than as I am in C++, I am not using sscanf(…) so it may or may not answer your request if you expect to use sscanf for your solution.

Here is the sample code:

#include <regex>
#include <iostream>

int main ()
{
    std::string val{"Element1 \t OptionalElement2 \t OptionalElement3"};
    //std::string val{"Element1 \t OptionalElement2"};
    //std::string val{"Element1"};

    // the match object
    std::smatch m;
    // declare regular expression for matching (note that optional elements are marked as optional with the ? after
    // closing parenthesis
    std::regex myreg("^\\s*([\\w\\d]+)\\s*([\\w\\d]+)?\\s*([\\w\\d]+)?\\s*$");

    // check if there the match between our pattern and the content
    if( std::regex_match(val, m, myreg) )
    {
        // here there will be 4 values available
        // m[0]: the full line
        // m[1]: element 1
        // m[2] : Optional element 2 or an empty string if not found
        // m[3] : Optional element 3 or an empty string if not found
        std::clog << "Size of results:" << m.size() << "\n";

        // display one element
        std::cout << "Element 1: " << m[1] << "\n";
        if( m[2].matched)
            std::cout << "Element 2: " << m[2] << "\n";

        if( m[3].matched)
            std::cout << "Element 3: " << m[3] << "\n";

        // if you want to display all matched elements, here is the code
        /*for (const auto& entry: m)
        {
            if( entry.matched)
                std::clog << "Found: " << entry.str() << "\n";
        }*/
    }

    return 0;
}

Again, given information at my disposal, it may not answer your request but at least you have a working C++ version now.

1

solved How to handle regular expression?