-1

Okay, so I am trying to learn c++ regular expressions and I am having some trouble with it. I went over the code, and at least to me, it makes logical sense. I also tested it online using a regex tester and it successfully matched my string. The first two(nameParser, and anotherNameParser) do NOT work, but the last one(sampleParser) does. I really do not understand why it is not validating my string. Below I included a screen shot: Screenshot showing output

//http://rextester.com/tester
//compile with g++ -std=gnu++11 main.cpp -o main
#include <iostream>
#include <regex>
using namespace std;

/* * (nameParser)
 * Beginning at the front of the string, any set of character followed by at least one or more spaces 
 * followed by any set of characters with exactly one preceding dot, 
 * then followed by at least one or more spaces followed by any set of characters and end of string
 */

 //Need the extended or basic because any version less than 4.9 doesn't fully support c++11 regular expressions (28.13).
 //The error is because creating a regex by default uses ECMAScript syntax for the expression, which doesn't support brackets.
const regex nameParser("^[a-zA-Z]+\\s+[a-zA-Z]\\.{1}\\s+[a-zA-Z]+$",regex::extended);
const regex anotherNameParser("[a-zA-Z]+",regex::extended);
const regex sampleParser("(abc)");

int main() {
    //simple regex testing
    string name = "bob R. Santiago";
    if(regex_match(name, nameParser)) {
        cout << "name is valid!" << endl;
    } else cout << "Error in valdiating name!" << endl;

    string anotherName = "Bobo";
    if(regex_match(anotherName, anotherNameParser)) {
            cout << "name is valid!" << endl;
    } else cout << "Error in valdiating name!" << endl;

    string sample = "abc";
    if(regex_match(sample, sampleParser)) {
            cout << "name is valid!" << endl;
    } else cout << "Error in valdiating name!" << endl;

    return 0;
}
Damian
  • 87
  • 2
  • 14

2 Answers2

6
//Need the extended or basic because gnu gcc-4.6.1 doesn't fully support c++11 regular expressions (28.13).

It doesn't support them at all until version 4.9, despite the presence of a <regex> header.

Sometimes it may appear to do what you want, but it basically doesn't.

Upgrade to GCC 4.9.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

Support for <regex> was not added until GCC 4.9. See the release notes:

Runtime Library (libstdc++)

  • Improved support for C++11, including:
    • support for <regex>;