运用 C# 正则表达式,精准验证邮箱格式

济南云服务器 2025年2月15日06:06:02C#教程运用 C# 正则表达式,精准验证邮箱格式已关闭评论111阅读模式

使用软件系统需要用户填写联系方式时,如果,用户填写的邮箱不正确,会导致出现很多问题,比如,密码找回等,下面济南网站建设小编通过正则表达式来检查用户输入的邮箱格式是否正确,如果,用户输入的邮箱格式正确,则提示用户输入的邮箱格式正确。

关键代码:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        // 定义验证邮箱格式的正则表达式模式
        string pattern = @"^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";

        // 测试用的输入字符串数组
        string[] testEmails = { "example@example.com", "invalid.email", "example@.com", "example@example", "example@123.45" };

        foreach (string email in testEmails)
        {
            // 使用 Regex.IsMatch 方法进行匹配
            bool isMatch = Regex.IsMatch(email, pattern);
            if (isMatch)
            {
                Console.WriteLine($"输入的邮箱地址 '{email}' 格式正确。");
            }
            else
            {
                Console.WriteLine($"输入的邮箱地址 '{email}' 格式不正确。");
            }
        }
    }
}

济南云服务器
  • 本文由 发表于 2025年2月15日06:06:02
  • 转载请务必保留本文链接:http://news.hcsw666.com/2010