Source of simple_regex_example_tr1.cpp


  1: //simple_regex_example_tr1.cpp
  2: //Validating simple user input with regular expressions.

  4: #include <iostream>
  5: #include <string>
  6: using namespace std;

  8: #include <regex>
  9: using std::tr1::regex;
 10: using std::tr1::regex_match;

 12: int main()
 13: {
 14:     //Get a valid Canadian postal code from the user
 15:     cout << "\nEnter a Canadian postal code: ";
 16:     string data;
 17:     getline(cin, data);
 18:     while (!regex_match(data, regex("[A-Z]\\d[A-Z] \\d[A-Z]\\d")))
 19:     {
 20:         cout << "\nThat was an invalid postal code.";
 21:         cout << "\nPlease enter another one: ";
 22:         getline(cin, data);
 23:     }
 24:     cout << "\nThat was a valid postal code. Thank you!";
 25:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 27:     //Get a valid 10-digit phone number from the user
 28:     cout << "\nEnter a 10-digit phone number (xxx-xxx-xxxx): ";
 29:     getline(cin, data);
 30:     while (!regex_match(data, regex("[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}")))
 31:     {
 32:         cout << "\nThat was an invalid phone number.";
 33:         cout << "\nPlease enter another one: ";
 34:         getline(cin, data);
 35:     }
 36:     cout << "\nThat was a valid phone number. Thank you!";
 37:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
 38: }