0

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();
}    
  • You are using an std::regex with the POSIX ERE flag. You must remove the flag (to use the default ECMAScript flavor), and you may also use [`distr(R"(\s*\(*\s*[1-9]\d*\s*\)*(?:\s*[-+*/]\s*\(*\s*[1-9]\d*\s*\)*)*\s*)")`](https://regex101.com/r/cJMo8R/2) – Wiktor Stribiżew Oct 09 '17 at 10:18
  • @WiktorStribiżew I removed 'std::regex_constants::extended' and changed distr to raw string, but the problem remains – Augustus Grin Oct 09 '17 at 13:41
  • Then it is most probably the most common thing: what is your GCC version? See [Is gcc 4.8 or earlier buggy about regular expressions?](http://stackoverflow.com/a/12665408/3832970) – Wiktor Stribiżew Oct 09 '17 at 13:43
  • You should really consider using C++11's [`Raw string literals`](http://en.cppreference.com/w/cpp/language/string_literal) – ZivS Oct 09 '17 at 19:02

0 Answers0