在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");
}
}
}
}
}