Regular expressions


#1

I am teaching C++ using an educational account with Cloud 9. One of my students reported a problem with regular expressions that I am unable to solve:

#include
#include
#include
#include

using namespace std;

int main()
{
// declare a variable to store the height
string name;

// ask the user for the height of the rectangle and store input
cout << "Name: ";
getline(cin, name);

// validate the user input
try
{
    regex validation("[a-z]|[A-Z]");
    cout << "regex compiled\n";
    while(!regex_search(name, validation))
    {
        cout << "Please enter an integer greater than 0." << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cin >> name;
    }
}
catch(regex_error& e)
{
    string message;
    cout << "Regex error: ";
    switch(e.code())
    {
        case regex_constants::error_collate: message = "invalid collating element name"; break;
        case regex_constants::error_ctype: message = "invalid character class name"; break;
        case regex_constants::error_escape: message = "invalid escaped character or a trailing escape"; break;
        case regex_constants::error_backref: message = "invalid back reference"; break;
        case regex_constants::error_brack: message = "mismatched square brackets ('[' and ']')"; break;
        case regex_constants::error_paren: message = "mismatched parentheses ('(' and ')')"; break;
        case regex_constants::error_brace: message = "mismatched curly braces ('{' and '}')"; break;
        case regex_constants::error_badbrace: message = "invalid range in a {} expression"; break;
        case regex_constants::error_range: message = "invalid character range (e.g. [b-a])"; break;
        case regex_constants::error_space: message = "not enough memory to convert expression"; break;
        case regex_constants::error_badrepeat: message = "one of *?+{ was not preceded by a valid expression"; break;
        case regex_constants::error_complexity: message = "complexity of an attempted match exceeded a predefined level"; break;
        case regex_constants::error_stack: message = "not enough memory to perform a match"; break;
        default: message = "unknown error";
    }
    cout << message << endl;
}
cout << "The name is " << name << endl;

}

When I run this, I get the following message:

Running /home/ubuntu/workspace/Regex/Regex.cpp
Name: Peter Pan
Regex error: mismatched square brackets (’[’ and ‘]’)
The name is Peter Pan

Process exited with code: 0

The regular expression is so simple, I cannot see what is wrong. So my conclusion that there is a bug in
Cloud 9. This is supported by the fact that when we try to debug this code, we get an error that “regex_compiler.h” cannot be found.

Please look into this.

Thank you.