判断邮箱格式是否正确(C#实现&&正则表达式实现)

时间:2025-03-10 09:28:53
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSHARP_TEST { class Program { //判断邮箱是否合法 static public bool judgeEmailAddress(string emailAddress) { //有“@” if (emailAddress.IndexOf("@")==-1) { Console.WriteLine("输入的字符串中 没有@ !"); return false; } //只有一个“@” if (emailAddress.IndexOf("@") != emailAddress.LastIndexOf("@")) { Console.WriteLine("输入的字符串中 有多个@ !"); return false; } //有“.” if (emailAddress.IndexOf(".") == -1) { Console.WriteLine("输入的字符串中 没有. !"); return false; } //“@”出现在第一个“.”之前 if (emailAddress.IndexOf("@") > emailAddress.IndexOf(".")) { Console.WriteLine("输入的字符串中 @没有出现在.之前!"); return false; } //“@”不可以是第一个元素 if (emailAddress.StartsWith("@")) { Console.WriteLine("输入的字符串中 @是第一个元素!"); return false; } //“.”不可以是最后一位 if (emailAddress.EndsWith(".")) { Console.WriteLine("输入的字符串中 .是最后一位!"); return false; } //不能出现“@.” if (emailAddress.IndexOf("@.") != -1) { Console.WriteLine("输入的字符串中 出现了@. !"); return false; } //不能出现“..” if (emailAddress.IndexOf("..") != -1) { Console.WriteLine("输入的字符串中 出现了.. !"); return false; } return true; } static void Main(string[] args) { string email_address; Console.WriteLine("请输入邮箱地址:"); email_address = Console.ReadLine(); //判断邮箱地址是否合法 if (judgeEmailAddress(email_address) == false) { Console.WriteLine("E-mail address is illegal !"); }else{ Console.WriteLine("输入格式正确!"); } } } }