日期:2014-05-17  浏览次数:21050 次

新手学习 C#控制台程序_邮箱地址验证
各位:
最进在学C#,从基础部分学起,现在遇到一个问题怎么都搞不了,请给位帮忙指点一下:最好能给出具体的代码
一、输入一个邮箱地址,然后将这个邮箱的用户名和域名分别输出
我现在已经可以正常输出用户名和域名,我就想在输入邮箱地址的时候做一个验证:验证所输入的数据是否格式正确(xxxx@xxx.com);想过用正则表达式,但我自己看的不是很明白,所以也用不了;另外一个就是在程序里面检测是否存在"@"和".com"字符串,但不知道怎么去验证。现在想请给位大大指点一下
具体程序代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions; namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string email;
int a;
Console.WriteLine("请输入一个邮箱地址:");
email = Convert.ToString(Console.ReadLine()); 
//想在这里加一个输入验证是否为正确的邮箱地址,如果是则正常运行,否则转回到输入提示那里
a = email.IndexOf("@"); 
string val1 = email.Substring(0, a);
string val2 = email.Substring(a+1, email.Length-a-1);
Console.WriteLine("所输入邮箱的用户名为:{0},域名为:{1}",val1,val2);
}
}
}


------解决方案--------------------
static void Main(string[] args)
{
string email;
int a;
Console.Write("请输入一个邮箱地址:");
email = Convert.ToString(Console.ReadLine());
a = email.IndexOf("@");
while (a == -1)
{
Console.WriteLine("邮件地址格式不正确!");
Console.Write("请重新输入一个邮箱地址:");
email = Convert.ToString(Console.ReadLine());
a = email.IndexOf("@");
}
string user = email.Substring(0, a);
string yu = email.Substring(a + 1, email.Length - a - 1);
Console.WriteLine("您所输入的邮箱的用户名为:{0},域名为:{1}",user,yu);
Console.ReadKey();
}
------解决方案--------------------
C# code
  while (a == -1)
  {
  Console.WriteLine("邮件地址格式不正确!");
  Console.Write("请重新输入一个邮箱地址:");
  email = Convert.ToString(Console.ReadLine());
  a = email.IndexOf("@");
  }
 string user = email.Substring(0, a);
string yu = email.Substring(a + 1, email.Length - a - 1);
if(yu==".com")
 Console.WriteLine("您所输入的邮箱的用户名为:{0},域名为:{1}",user,yu);
Console.ReadKey();

------解决方案--------------------
用正则表达式:只要是拼写正则表达式:我看了下这正则是正确的。在用微软的类库:Regex.IsMatch做判断
代码大概如下:
C#版本
private void cmdConfirm_Click(object sender, System.EventArgs e)
{
string pattern = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
string strEmail = TextBox1.Text.Trim();
if( System.Text.RegularExpressions.Regex.IsMatch(strEmail ,pattern) )
{
Response.Write("<script>alert('正确!');</script>"); }
else
{
Response.Write("<script>alert('错误!');</script>"); }
}

VS2005中邮箱正则表达式

今天需要一个关邮电子邮箱输入的正则表达式,于是在控制台程序做了一个测试
static void Main(string[] args)
{
string emailPattern = @"^([a-z0-9A-Z]+[-|\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-zA-Z]{2,}$";
Console.Write("Enter an e-mail address:");
string emailInput = Console.ReadLine();
bool match = Regex.IsMatch(emailInput, emailPattern);
if (match)
{
Console.WriteLine("E-mail address is valid");
Console.ReadLine();
}
else
{
Console.WriteLine("Suppliied input is not a valid e-mail address");
Console.ReadLine();
}