C++正则表达式校验某个字符串是否是合格的email
可以借助正则表达式校验某个字符串是否是合规的电子邮箱。对于邮箱的正则表达式有严格的模式,如:^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$
对应的C++实现如下:
// EmailValidator.h
#ifndef EMAIL_VALIDATOR_H
#define EMAIL_VALIDATOR_H
#include <string>
// Email地址校验类
class EmailValidator
{
public:
// 校验email是否是合法的email地址
static bool isValidEmail(const std::string& email);
};
#endif // EMAIL_VALIDATOR_H
// EmailValidator.cpp
#include "EmailValidator.h"
#include <regex>
namespace {
const std::string EMAIL_PATTERN = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*" \
"@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
}
bool EmailValidator::isValidEmail(const std::string& email)
{
std::regex pattern(EMAIL_PATTERN);
// Tests whether a regular expression matches the entire target string.
if (std::regex_match(email, pattern)) {
return true;
}
return false;
}
//测试main.cpp
#include "EmailValidator.h"
#include <iostream>
using namespace std;
// C++11标准 STL正则表达式 验证电子邮件地址
// https://blog.csdn.net/kyfvc/article/details/41082025
int main(int argc, char* argv[])
{
std::string emailAddress;
// while (std::getline(cin, emailAddress))
while (cin >> emailAddress)
{
if (EmailValidator::isValidEmail(emailAddress)) {
std::cout << "您输入的电子邮件地址: " << emailAddress << " 合法" << std::endl;
} else {
std::cout << "您输入的电子邮件地址: " << emailAddress << " 不合法" << std::endl;
}
}
return 0;
}
运行结果如下图所示: