在C#中用正则表达式需要引用using System.Text.RegularExpressions,在写正则表达式时要先写一个@
例如 string email = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";不然提示转义出现错误
string emailinput = Console.ReadLine();
判断是否匹配时,bool match = Regex.IsMatch(emailInput , email)
//Regex.IsMatch(string input , string pattern);注意参数的顺序。
代码:
namespace test2
{
class Program
{
static void Main(string[] args)
{
string email = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";//
while (true)
{
Console.Write("input:");
string emailInput = Console.ReadLine();
bool match = Regex.IsMatch(emailInput, email);
if (match)
{
Console.WriteLine("legal");
}
else
{
Console.WriteLine("illegal");
}
}
}
}
}
本文介绍如何在C#中使用正则表达式验证邮箱地址的有效性,包括匹配邮箱格式的基本步骤和示例代码。

被折叠的 条评论
为什么被折叠?



