Link to home
Start Free TrialLog in
Avatar of ambuli
ambuliFlag for United States of America

asked on

Regular expression to filter out time and date

Hi there,

I need to separate day, month, year, hour, min from a string in the following format.  How can I do this using Regular Expressions.  Thank you.
18.06.2015 22:17
SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ambuli

ASKER

Thanks, but how about using C++?
Avatar of ambuli

ASKER

I came up with this one.  Not sure if there is any issues.  Seems to work for now.

#include <boost/regex.hpp>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    boost::regex pattern("(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2})");
    boost::match_results<std::string::const_iterator> matches;
    if(0 != boost::regex_match(string("1994-10-21 14:41"), matches, pattern))
    {
        cout << "pattern matches...." << endl;
        string value1(matches[1].first, matches[1].second);
        string value2(matches[2].first, matches[2].second);
        string value3(matches[3].first, matches[3].second);
        string value4(matches[4].first, matches[4].second);
        string value5(matches[5].first, matches[5].second);

        cout << value1 << ", " << value2 << "," << value3 << "," << value4 << "," << value5 << endl;

    }
    else
    {
        cout << "No matching string found" << endl;
    }

    //cout << MSG << endl;

    return 0;
}

Open in new window

Don't want to be nitpicking, but that seems like using a sledgehammer to crack a nut... I mean two lines 'sscanf()' using standard libraries vs. 25 lines and using boost ;o)

Nothing against boost, if you are already using it in your project, this does not make a big difference. but if you'd had to add it just for this task, I wouldn't do it.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ambuli

ASKER

Thank you all.  Yes, I was doing something in the same class with boost so I thought of doing that way.  Yes, it is unnecessary .
Yes, it is unnecessary .
of course not. boost regular expressions is a mighty tool and it is of course worth to make some experiences with it. the c solution jkr has posted and the c++ way i provided only can show that there are more than one way to achieve a goal. if you try all alternatives you finally can find out what is the best (for you).

Sara
Avatar of ambuli

ASKER

Thank you Sara