lundi 9 octobre 2017

c++ regex match doesn't work as intended

I have a pretty simple task: read an equation from a file and then use it in further algorithms. I need to check if the equation the file contains is correct, so I use regex for this. Regex represents the whole string from the file, that's why I use regex_match. But I keep getting false results. For example, I have ((4563722- 5764545 ) * ( 657457 + 75477) -647586 )+ 748785 /5 in my file, and it doesn't match the regex as it should. I have googled a lot about my problem, but no suggested solution worked for me.

I use the last version Qt creator with mingw32 on Windows. Thanks in advance.

#include <QCoreApplication>
#include<iostream>
#include<fstream> 
#include<string> 
#include<stdio.h> 
#include<regex>
using namespace std;

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ifstream FILE;
string filename, equation, check;

const regex distr(("\\s*\\(*\\s*[123456789]\\d*\\s*\\)*(\\s*[\\+\\-\\*\\/]\\s*\\(*\\s*[123456789]\\d*\\s*\\)*\\s*)*"), std::regex_constants::extended);

do{
    cout << "Input name of file" << endl;
    getline(cin, filename);
    FILE.open(filename.c_str());
    if (!FILE.is_open())
        cout << "Error. Cannot open file" << endl;
    else{
        getline(FILE, check);
        if(FILE.eof() && check.empty()){
            cout << "Error. File is empty" << endl;
            FILE.close();
        }
    }
}while((!FILE.is_open())||(check.empty()));
FILE.close();
FILE.open(filename.c_str());
getline(FILE, equation);
cout << equation << endl;
FILE.close();
if (regex_match(equation, distr))
    cout << "True" << endl;
else
    cout << "False" << endl;
return a.exec();
}    

Aucun commentaire:

Enregistrer un commentaire