Regular Expression Quantifiers - C++ Regular Expression

C++ examples for Regular Expression:Match

Introduction

Quantifier Matches
* Matches zero or more occurrences of the preceding pattern.
+ Matches one or more occurrences of the preceding pattern.
? Matches zero or one occurrences of the preceding pattern.
{n} Matches exactly n occurrences of the preceding pattern.
{n,}Matches at least n occurrences of the preceding pattern.
{n,m} Matches between n and m (inclusive) occurrences of the preceding pattern.

Demo Code

#include <iostream> 
#include <string> 
#include <regex> 
using namespace std; 

bool validate( const string&, const string& ); // validate prototype 
string inputData( const string&, const string& ); // inputData prototype 

int main() /*from   w w  w  .  j  a v a  2s .  co m*/
{ 
    // enter the last name 
    string lastName = inputData( "last name", "[A-Z][a-zA-Z]*" ); 

    // enter the first name 
    string firstName = inputData( "first name", "[A-Z][a-zA-Z]*" ); 

   // enter the address 
   string address = inputData( "address", "[0-9]+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" ); 

   // enter the city 
   string city = inputData( "city", "([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" ); 

   // enter the state 
   string state = inputData( "state", "([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" ); 

   // enter the zip code 
   string zipCode = inputData( "zip code", "\\d{5}" ); 

   // enter the phone number 
   string phoneNumber = inputData( "phone number", "[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}" ); 

   cout << "\nValidated Data\n\n" 
       << "Last name: " << lastName << endl 
       << "First name: " << firstName << endl 
       << "Address: " << address << endl 
       << "City: " << city << endl 
       << "State: " << state << endl 
       << "Zip code: " << zipCode << endl 
       << "Phone number: " << phoneNumber << endl; 
}

// validate the data format using a regular expression 
bool validate( const string &data, const string &expression ) { 
   regex validationExpression = regex( expression ); 
   return regex_match( data, validationExpression ); 
}

// collect input from the user 
string inputData( const string &fieldName, const string &expression ) { 
   string data; // store the data collected 

   // request the data from the user 
   cout << "Enter " << fieldName << ": "; 
   getline( cin, data ); 

   // validate the data 
   while ( !( validate( data, expression ) ) ) 
   { 
       cout << "Invalid " << fieldName << ".\n" ; 
       cout << "Enter " << fieldName << ": "; 
        getline( cin, data ); 
    }

    return data; 
}

Result


Related Tutorials