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:
//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;
}