-1

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.

Community
  • 1
  • 1
William S
  • 145
  • 6
  • 2
    Your regex matches __zero__ or more digits. Your empty match is a valid result. Try `\d+`. – tkausl Nov 23 '19 at 14:53

1 Answers1

0

As the comment says, if you change \\d* to \\d+, it will work,

#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;
}

The output is Enter a date in form of mm/dd/yyyy: 11/12/2019

11

/12/2019

12

CS Pei
  • 10,211
  • 1
  • 23
  • 41