#include <iostream>
#include <regex>
#include <string>
int main() {
// 定义一个正则表达式,用于匹配电子邮件地址
std::regex email_regex(R"(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b)", std::regex_constants::icase);
// 测试字符串
std::string test_str = "My email is example@example.com and your email is test@domain.org";
// 使用 std::sregex_iterator 查找所有匹配项
auto words_begin = std::sregex_iterator(test_str.begin(), test_str.end(), email_regex);
auto words_end = std::sregex_iterator();
// 输出所有匹配的电子邮件地址
for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
std::smatch match = *i;
std::string match_str = match.str();
std::cout << "Found email: " << match_str << '\n';
}
return 0;
}
#include <regex>
引入了 C++ 标准库中的正则表达式支持。std::regex
定义了一个用于匹配电子邮件地址的正则表达式。这里的正则表达式 \b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b
可以匹配常见的电子邮件格式,并且忽略了大小写(通过 std::regex_constants::icase
)。test_str
。std::sregex_iterator
来遍历并查找字符串中所有与正则表达式匹配的部分。这个示例展示了如何在 C++ 中使用正则表达式来查找和处理文本中的特定模式。
上一篇:c++ 重载运算符
下一篇:c++getline
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站