Regex Email validation

后端 未结 30 1216
北海茫月
北海茫月 2020-11-22 12:16

I use this

@\"^([\\w\\.\\-]+)@([\\w\\-]+)((\\.(\\w){2,3})+)$\"

regexp to validate the email

([\\w\\.\\-]+) - this is f

30条回答
  •  春和景丽
    2020-11-22 12:37

    There's no perfect regular expression, but this one is pretty strong, I think, based on study of RFC5322. And with C# string interpolation, pretty easy to follow, I think, as well.

    const string atext = @"a-zA-Z\d!#\$%&'\*\+-/=\?\^_`\{\|\}~";
    var localPart = $"[{atext}]+(\\.[{atext}]+)*";
    var domain = $"[{atext}]+(\\.[{atext}]+)*";
    Assert.That(() => EmailRegex = new Regex($"^{localPart}@{domain}$", Compiled), 
    Throws.Nothing);
    

    Vetted with NUnit 2.x.

提交回复
热议问题