c++ regex to validate indian phone number pattern
#include <iostream>
#include <regex>
int main() {
std::string phoneNumber;
// Get input phone number
std::cout << "Enter Indian phone number: ";
std::cin >> phoneNumber;
// Define Indian phone number pattern
std::regex indianPhoneNumberPattern("^\\+91[1-9][0-9]{9}$");
// Validate the input phone number
if (std::regex_match(phoneNumber, indianPhoneNumberPattern)) {
std::cout << "Valid Indian phone number." << std::endl;
} else {
std::cout << "Invalid Indian phone number." << std::endl;
}
return 0;
}
Explanation:
#include <iostream>
: Include the necessary header files for input and output operations.#include <regex>
: Include the header file for regular expressions.int main() { ... }
: The main function where the program execution begins.std::string phoneNumber;
: Declare a string variable to store the input phone number.std::cout << "Enter Indian phone number: ";
: Prompt the user to enter an Indian phone number.std::cin >> phoneNumber;
: Read the input phone number from the user.std::regex indianPhoneNumberPattern("^\\+91[1-9][0-9]{9}$");
: Define a regular expression pattern for validating Indian phone numbers.^
: Assert the start of the string.\\+91
: Match the country code for India, which is "+91".[1-9]
: Match the first digit of the phone number, which cannot be 0.[0-9]{9}
: Match the next 9 digits of the phone number.$
: Assert the end of the string.if (std::regex_match(phoneNumber, indianPhoneNumberPattern)) { ... }
: Check if the entered phone number matches the defined Indian phone number pattern.std::cout << "Valid Indian phone number." << std::endl;
: If the phone number is valid, display a message indicating that it is valid.} else { std::cout << "Invalid Indian phone number." << std::endl; }
: If the phone number is not valid, display a message indicating that it is invalid.return 0;
: Return 0 to indicate successful program execution.