Skip to content

Instantly share code, notes, and snippets.

@jflopezfernandez
Last active May 7, 2018 10:59
Show Gist options
  • Save jflopezfernandez/915301eac02095efff8e6f097a03bb9d to your computer and use it in GitHub Desktop.
Save jflopezfernandez/915301eac02095efff8e6f097a03bb9d to your computer and use it in GitHub Desktop.
Using C++ Standard Library regular expressions to find phone numbers in most common formats
#include <iostream>
#include <regex>
#include <string>
#include <vector>
int main(int argc, char *argv[])
{
const std::string defaultRegex { "\\(?\\d{3}[-\\) ]+\\d{3}[- ]?\\d{4}" };
std::regex phoneNumberRegex;
if (argc == 1)
{
std::cout << "[No regex supplied, using default]: /" << defaultRegex << "/\n";
phoneNumberRegex = defaultRegex;
} else
{
phoneNumberRegex = std::regex { argv[1] };
}
const std::vector<std::string> phoneNumbers = {
"813-555-0123",
"012 344 0123",
"(813) 234-0211",
"(124)888-1002"
};
for (const auto& phoneNumber : phoneNumbers)
{
std::cout << "[" << phoneNumber << "]: " << std::boolalpha << std::regex_match(phoneNumber, phoneNumberRegex) << "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment