RDismyname
RDismyname

Reputation: 183

Retrieving a regex search in C++

Hello I am new to regular expressions and from what I understood from the c++ reference website it is possible to get match results.

My question is: how do I retrieve these results? What is the difference between smatch and cmatch? For example, I have a string consisting of date and time and this is the regular expression I wrote:

"(1[0-2]|0?[1-9])([:][0-5][0-9])?(am|pm)"

Now when I do a regex_search with the string and the above expression, I can find whether there is a time in the string or not. But I want to store that time in a structure so I can separate hours and minutes. I am using Visual studio 2010 c++.

Upvotes: 16

Views: 48123

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409136

If you use e.g. std::regex_search then it fills in a std::match_result where you can use the operator[] to get the matched strings.

Edit: Example program:

#include <iostream>
#include <string>
#include <regex>

void test_regex_search(const std::string& input)
{
    std::regex rgx("((1[0-2])|(0?[1-9])):([0-5][0-9])((am)|(pm))");
    std::smatch match;

    if (std::regex_search(input.begin(), input.end(), match, rgx))
    {
        std::cout << "Match\n";

        //for (auto m : match)
        //  std::cout << "  submatch " << m << '\n';

        std::cout << "match[1] = " << match[1] << '\n';
        std::cout << "match[4] = " << match[4] << '\n';
        std::cout << "match[5] = " << match[5] << '\n';
    }
    else
        std::cout << "No match\n";
}

int main()
{
    const std::string time1 = "9:45pm";
    const std::string time2 = "11:53am";

    test_regex_search(time1);
    test_regex_search(time2);
}

Output from the program:

Match
match[1] = 9
match[4] = 45
match[5] = pm
Match
match[1] = 11
match[4] = 53
match[5] = am

Upvotes: 25

kuperspb
kuperspb

Reputation: 339

Just use named groups.

(?<hour>(1[0-2]|0?[1-9]))([:](?<minute>[0-5][0-9]))?(am|pm)

Ok, vs2010 doesn't support named groups. You already using unnamed capture groups. Go through them.

Upvotes: 1

Related Questions