regex for phone number c++

C++ Regex for Phone Number

#include <iostream>
#include <regex>

int main() {
    std::string phoneNumber = "123-456-7890";
    std::regex pattern("\\b\\d{3}-\\d{3}-\\d{4}\\b");

    if (std::regex_search(phoneNumber, pattern)) {
        std::cout << "Valid phone number format" << std::endl;
    } else {
        std::cout << "Invalid phone number format" << std::endl;
    }

    return 0;
}

Explanation

  1. Include Libraries:
  2. #include <iostream>: Includes the input/output stream library.
  3. #include <regex>: Includes the regular expression library.

  4. Main Function:

  5. std::string phoneNumber = "123-456-7890";: Defines a string variable phoneNumber with the value "123-456-7890".
  6. std::regex pattern("\\b\\d{3}-\\d{3}-\\d{4}\\b");: Defines a regular expression pattern using std::regex. This pattern matches the format of a phone number in the form of "123-456-7890".

  7. Regex Search:

  8. if (std::regex_search(phoneNumber, pattern)) { ... }: Checks if the phoneNumber matches the regular expression pattern.
  9. If the phone number matches the pattern, it prints "Valid phone number format".
  10. If the phone number does not match the pattern, it prints "Invalid phone number format".

  11. Return:

  12. return 0;: Indicates successful completion of the program.