samedi 23 novembre 2019

C++ cannot parse date with regex - only matches month (the first number)

I am trying to use a simple regular expression to parse date in form of 10/10/2010. The regex I am using is date_re("\d*"). After the first match of 10, I reset the string to search to the match object suffix, which is correct /10/2010, but my regex no longer works on this string. I was assuming it would find the next 10.

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

int main() {
   std::string dateIn;
   std::regex date_re("\\d*");

   std::cout << "Enter a date in form of mm/dd/yyyy: ";
   std::getline(std::cin,dateIn);
   std::smatch matches;

   std::regex_search(dateIn,matches,date_re);

   std::cout << matches[0] << std::endl;
   std::cout << matches.suffix().str() << "\n\n";

   dateIn = matches.suffix().str();
   std::regex_search(dateIn,matches,date_re);

   std::cout << matches[0] << std::endl;
}

I had a while loop doing this but it was infinite loop. With input 10/10/2010 my output is

10

/10/2010

My last output statement does not print anything. Can someone help with my regex issue? Specifically I am looking for a regex that will parse all three numbers from the date.

Aucun commentaire:

Enregistrer un commentaire