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:

  1. #include <iostream>: Include the necessary header files for input and output operations.

  2. #include <regex>: Include the header file for regular expressions.

  3. int main() { ... }: The main function where the program execution begins.

  4. std::string phoneNumber;: Declare a string variable to store the input phone number.

  5. std::cout << "Enter Indian phone number: ";: Prompt the user to enter an Indian phone number.

  6. std::cin >> phoneNumber;: Read the input phone number from the user.

  7. std::regex indianPhoneNumberPattern("^\\+91[1-9][0-9]{9}$");: Define a regular expression pattern for validating Indian phone numbers.

  8. ^: Assert the start of the string.
  9. \\+91: Match the country code for India, which is "+91".
  10. [1-9]: Match the first digit of the phone number, which cannot be 0.
  11. [0-9]{9}: Match the next 9 digits of the phone number.
  12. $: Assert the end of the string.

  13. if (std::regex_match(phoneNumber, indianPhoneNumberPattern)) { ... }: Check if the entered phone number matches the defined Indian phone number pattern.

  14. std::cout << "Valid Indian phone number." << std::endl;: If the phone number is valid, display a message indicating that it is valid.

  15. } else { std::cout << "Invalid Indian phone number." << std::endl; }: If the phone number is not valid, display a message indicating that it is invalid.

  16. return 0;: Return 0 to indicate successful program execution.