0

I want to check date format in a string, so I use std::regex in c++;

I goggled some demo, but they all failed to me, includes:

#include <iostream>                                                                                                                                                                         
#include <regex>

using namespace std;

int main() {
    string text = "future2018-7-12";
    // regex  pattern("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}");  // these three all failed
    // regex  pattern("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}");
    std::regex pattern("\\b\\d{4}[-]\\d{2}[-]\\d{2}\\b");

    smatch results;
    if ( regex_match(text, results, pattern) ) { 
        smatch::iterator it = results.begin();
        int i = 0;
        for(; it != results.end(); ++it, ++i)
            cout<<i<<": "<<*it<<endl;
    } else {
        cout << "match failed: " <<text<< endl;
    }   
    return 0;
}

my compile command is:

g++ -std=c++11 reg.cpp -o reg

execute command is:

./reg

my machine is:

centos 7 in vmware

they all crashed with the error:

terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error

that confuses me, because i can only find these demo about regex.

So, what wrong with my code?

nick
  • 41
  • 6
  • Both programs work for me (linux gcc 8.3). Please tell us about your environment/compiler including adding the relevant tags. – Allan Wind Feb 27 '21 at 03:25
  • Also please remove one of the programs so we know which you are focused on. – Allan Wind Feb 27 '21 at 03:28
  • @AllanWind added, thanks – nick Feb 27 '21 at 03:31
  • What version of gcc? (What is the output of `g++ --version`?) – Marshall Clow Feb 27 '21 at 04:01
  • Does this answer your question? [Is gcc 4.8 or earlier buggy about regular expressions?](https://stackoverflow.com/questions/12530406/is-gcc-4-8-or-earlier-buggy-about-regular-expressions) – xskxzr Feb 27 '21 at 05:01
  • This behavior is probably due to a problematic installation of CentOS. Or possibly of VM Ware. I've seen very strange errors in WSL (aka Windows Subsystem for Linux), but both CentOS and VmWare have good reputations. When compiling software with strange behavior, it is always a good idea to enable every compilation warning that you can. In the case of g++, that would be `g++ -std=c++11 -W -Wall` `g++ -std=c++11 -W -Wall reg.cpp -o reg` – Hilton Fernandes Feb 27 '21 at 15:48

0 Answers0