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
- Include Libraries:
#include <iostream>
: Includes the input/output stream library.#include <regex>
: Includes the regular expression library.Main Function:
std::string phoneNumber = "123-456-7890";
: Defines a string variablephoneNumber
with the value "123-456-7890".std::regex pattern("\\b\\d{3}-\\d{3}-\\d{4}\\b");
: Defines a regular expression pattern usingstd::regex
. This pattern matches the format of a phone number in the form of "123-456-7890".Regex Search:
if (std::regex_search(phoneNumber, pattern)) { ... }
: Checks if thephoneNumber
matches the regular expression pattern.- If the phone number matches the pattern, it prints "Valid phone number format".
If the phone number does not match the pattern, it prints "Invalid phone number format".
Return:
return 0;
: Indicates successful completion of the program.