HOW TO:確認字串是否為有效的電子郵件格式
更新:2007 年 11 月
下列程式碼範例使用靜態 Regex.IsMatch 方法驗證字串是否為有效的電子郵件格式。如果字串中包含有效的電子郵件地址,IsValidEmail 方法會傳回 True;如果沒有,則傳回 False,而不會做其他的動作。當應用程式將地址儲存到資料庫中或將其顯示在 ASP.NET 網頁之前,可以使用 IsValidEmail 篩選掉包含無效字元的電子郵件地址。
範例
Imports System.Text.RegularExpressions
Module Example
Function IsValidEmail(strIn As String) As Boolean
' Return true if strIn is in valid e-mail format.
Return Regex.IsMatch(strIn, _
"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")
End Function
End Module
using System;
using System.Text.RegularExpressions;
public class Example
{
bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn,
@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
}