C# 中的正则表达式电子邮件验证器出现问题
我使用以下代码来验证数组中存在的电子邮件地址。但是,在成功验证数组中的第一个电子邮件地址后,下一个电子邮件地址始终返回 false。我可以知道为什么它会这样吗?
public static bool IsValidEmailID(string email)
{
string MatchEmailPattern =
@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
Regex reStrict = new Regex(MatchEmailPattern);
return reStrict.IsMatch(email);
}
更新 : 以下代码从 Windows 窗体文本框中获取电子邮件地址:
String[] EmailArr = txtEmailID.Text.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
for(int i = 0; i < EmailArr.Length; i++)
{
MessageBox.Show(IsValidEmailID(EmailArr[i])+" "+EmailArr[i]);
}
I'm using the following code for validating email address which are present in an array. But after successfully validating first email address in an array, it is always returning false for next email address. May I know why it is behaving like that?
public static bool IsValidEmailID(string email)
{
string MatchEmailPattern =
@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
Regex reStrict = new Regex(MatchEmailPattern);
return reStrict.IsMatch(email);
}
Update :
The following code is getting email address from windows form text box:
String[] EmailArr = txtEmailID.Text.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
for(int i = 0; i < EmailArr.Length; i++)
{
MessageBox.Show(IsValidEmailID(EmailArr[i])+" "+EmailArr[i]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这种验证方法工作正常。我创建了一个 ArrayList 并循环遍历数组,我正在调用您的方法来验证电子邮件。这是示例循环:
第一次结果等于 true,第二次结果等于 false,第三次结果等于 true。您使用什么类型的集合?也许除了第一封之外的所有电子邮件都无效......?
更新:
我用你的代码进行了测试,
你的分割效果很好。我唯一建议的想法是在验证之前修剪字符串。文本框有时会有一些额外的空格,这可能会导致问题。
This validation method works OK. I created an ArrayList and looping through array I'm calling your method to validate email. Here is sample loop:
First time result equals to true, second to false and third to true. What kind of collection are you using? Maybe all emails except the first one are invalid....?
UPDATE:
I tested with your code
Your split works well. The only think I may suggest is to trim string before validating. Textboxes sometimes have some extra spaces, which may cause issues.