2017-02-24 73 views
-2

下面的正則表達式不驗證如果電子郵件地址有在最後一個句號。 E.G [email protected]。 如果我通過這個電子郵件地址作爲參數strEmail向IsValidEmailAddress函數,該函數將返回true。它應該返回false如何驗證使用正則表達式尾句號電子郵件地址?

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

private bool IsValidEmailAddress(string strEmail) 
{ 
    System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(strEmail.Trim().ToLower(), MatchEmailPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); 

    if (!match.Success) 
    { 
     return false; 
    } 
    return true; 
} 

我非常感謝關於如何處理尾隨句號的建議。

+0

https://msdn.microsoft.com/en-us/library/01escwtf(v=vs.110).aspx – bolov

+0

http://stackoverflow.com/questions/1365407/c-sharp-code-to-驗證電子郵件地址 – bolov

回答

4

您需要令牌「字符串的結束」添加到你的正則表達式模式

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

...並使它到最後,還添加了「字符串的開始」令牌:

const 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})$"; 
相關問題