【正規表現】メールアドレス形式のチェック
ローカル部分では、通常のアルファベット、数字、特定の記号をサポートし、ピリオドを含むが連続しないこと。
ローカル部分でダブルクォーテーションを使用したクォートされた文字列をサポート。
ドメイン部分では、通常のドメイン名に加えて、IPアドレス形式のドメインもサポート。
#include <iostream>
#include <regex>
#include <string>
bool isValidEmailAddress(const std::string& email) {
// RFC 5322の規格に準拠した正規表現の上記など何点か盛り込んだもの
const std::regex pattern(
R"((?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}|(?:\d{1,3}\.){3}\d{1,3}|(?:\[[0-9a-fA-F:.]{7,}\])))"
);
// 簡略化されたメールアドレスの正規表現パターン
const std::regex pattern(
R"(^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$)"
);
return std::regex_match(email, pattern);
}
int main() {
std::string email = "example@example.com";
if (isValidEmailAddress(email)) {
std::cout << email << " is a valid email address." << std::endl;
} else {
std::cout << email << " is not a valid email address." << std::endl;
}
return 0;
}