Search code examples
c++regexstructdata-conversion

How do I convert a regular expression match into a "struct"?


Regular Expression: ([0-9]*)|([0-9]*\.[0-9]*)
String: word1 word2 0:12:13.23456 ... example string match: 0,12,13.23456

Requirement:
convert to a struct ->

struct Duration {
    unsigned int hours;
    unsigned int minutes;
    double seconds;
};

Current matcher:

Duration duration;
std::regex regex("([0-9]*):([0-9]*):([0-9]*.[0-9]*)");
auto begin = std::sregex_iterator(data.begin(), data.end(), regex); // data is an std::string instance
auto end = std::sregex_iterator();
for (auto it = begin; it != end; it++) {
    auto match = *it;
    // how to cycle through the data values of the instance of Duration?            
}

Solution

  • I recommend using std::regex_search instead of iterators and loops. Then you get a match result which you can index to get the separate matches.

    Once you have the separate matches, you can call std::stoul or std::stod to convert the matched strings to their numeric variants.

    Perhaps something like this:

    #include <iostream>
    #include <string>
    #include <regex>
    
    struct Duration
    {
        unsigned int hours;
        unsigned int minutes;
        double seconds;
    };
    
    int main()
    {
        std::string input = "word1 word2 0:12:13.23456";
        std::regex regex("([0-9]*):([0-9]*):([0-9]*.[0-9]*)");
        std::smatch matches;
    
        std::regex_search(input, matches, regex);
    
        Duration duration = {
            static_cast<unsigned int>(std::stoul(matches[1])),
            static_cast<unsigned int>(std::stoul(matches[2])),
            std::stod(matches[3])
        };
    
        std::cout << "Duration = { " << duration.hours << ", " << duration.minutes << ", " << duration.seconds << " }\n";
    }
    

    [Note: There's no error checking, or checking the amount of actual matches in matches, which should really be done in a "real" program]