C++ Regex 邮箱校验

本文提供了一个使用正则表达式验证电子邮件地址有效性的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <regex>
#include <iostream>
#include <string>

bool is_email_valid(const std::string& email)
{
   // define a regular expression
   const std::tr1::regex pattern
      ("(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+");

   // try to match the string with the regular expression
   return std::tr1::regex_match(email, pattern);
}

int main()
{
   std::string email1 = "marius.bancila@domain.com";
   std::string email2 = "mariusbancila@domain.com";
   std::string email3 = "marius_b@domain.co.uk";
   std::string email4 = "marius@domain";

   std::cout << email1 << " : " << (is_email_valid(email1) ?
      "valid" : "invalid") << std::endl;
   std::cout << email2 << " : " << (is_email_valid(email2) ?
      "valid" : "invalid") << std::endl;
   std::cout << email3 << " : " << (is_email_valid(email3) ?
     "valid" : "invalid") << std::endl;
   std::cout << email4 << " : " << (is_email_valid(email4) ?
     "valid" : "invalid") << std::endl;

   return 0;
}


转帖:http://ubuntuforums.org/showthread.php?t=1114404

C++ 中,`<regex>` 库提供了正则表达式支持,允许用户进行模式匹配、搜索、替换等操作。以下是一个简单的示例,展示了如何使用 C++ 的正则表达式库来匹配字符串: ```cpp #include <iostream> #include <regex> #include <string> int main() { std::string text = "The quick brown fox jumps over the lazy dog."; std::regex pattern("quick.*fox"); if (std::regex_search(text, pattern)) { std::cout << "Pattern found in the text." << std::endl; } else { std::cout << "Pattern not found in the text." << std::endl; } return 0; } ``` 在这个示例中,我们定义了一个字符串 `text` 和一个正则表达式模式 `quick.*fox`,然后使用 `std::regex_search` 函数来检查这个模式是否存在于 `text` 中。如果找到匹配的模式,程序将输出 "Pattern found in the text.",否则输出 "Pattern not found in the text."。 ### 注意事项 1. **正则表达式语法**:C++ 使用 ECMAScript 语法作为默认的正则表达式语法。 2. **性能考虑**:正则表达式操作可能会比较耗时,特别是在处理大量文本时。 3. **异常处理**:如果正则表达式语法不正确,`std::regex` 构造函数可能会抛出 `std::regex_error` 异常。 ### 扩展功能 C++ 的 `<regex>` 库还提供了其他有用的功能,例如: - `std::regex_match`:检查整个字符串是否匹配正则表达式。 - `std::regex_replace`:替换字符串中匹配正则表达式的部分。 - `std::smatch` 和 `std::cmatch`:用于存储匹配结果的类。 ### 示例:使用 `std::regex_replace` ```cpp #include <iostream> #include <regex> #include <string> int main() { std::string text = "The quick brown fox jumps over the lazy dog."; std::regex pattern("fox"); std::string replacement = "cat"; std::string new_text = std::regex_replace(text, pattern, replacement); std::cout << new_text << std::endl; return 0; } ``` 在这个示例中,我们将字符串中的 "fox" 替换为 "cat",并输出结果。 ### 总结 C++ 的 `<regex>` 库提供了强大的正则表达式功能,可以用于文本处理和模式匹配。使用时需要注意正则表达式的语法和性能问题,并适当处理可能的异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值