samedi 26 septembre 2015

Match a function-like input with std::regex

I want to process a function-like input with C++'s std::regex. I mean, something like this: sum(0,1,3,5) or prod(2,4,6,7).

Here is the code:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <regex>

using namespace std;

int main(int argc,char *argv[])
{
    string input;
    try
    {
        regex func("(sum|prod)\\((\\d,)*\\d\\)",regex::ECMAScript); // The pattern
        cin >> input;
        if (regex_match(input,func))
        {
            // do something
        }
        else
            cout << "Format is not valid." << endl;
    }
    catch (regex_error &e)
    {
        cout << "Regex error." << endl;
    }
}

But when I try it with the inputs said above, it gives an error. How can I correct the pattern?

Also, the compiler I used is g++, with the -std=c++0x flag.

Aucun commentaire:

Enregistrer un commentaire