2017-07-27 113 views
-1

我很難形成正則表達式來檢查隨機單詞字符串是否包含電子郵件地址。例如:檢查字符串是否包含電子郵件地址

string str = "Hello, thank you for viewing my ad. Please contact me on the phone number below, or at [email protected]" 

=匹配

string str - "Hello, thank you for viewing my ad. Please contact me on the phone number below" 

=不匹配

如何檢查一個字符串是否包含使用正則表達式的電子郵件地址?任何幫助將不勝感激。

+9

你試過了哪些正則表達式? – Sheldon

+4

相關https://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address?rq=1 – Scroog1

回答

0

用於檢索嚴格性不同的電子郵件地址有很多RegEx變體。只需按照鏈接並根據您的需求選擇合適的鏈接即可。 http://www.regular-expressions.info/email.html

對於大多數的需求在未來模式可以用來

Regex pattern = new Regex(@" 
          \b     #begin of word 
          (?<email>   #name for captured value 
           [A-Z0-9._%+-]+ #capture one or more symboles mentioned in brackets 
           @    #@ is required symbol in email per specification 
           [A-Z0-9.-]+  #capture one or more symboles mentioned in brackets 
           \.    #required dot 
           [A-Z]{2,}  #should be more then 2 symboles A-Z at the end of email 
          ) 
          \b     #end of word 
            ", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase); 

      var match = pattern.Match(input); 
      if (match.Success) 
      { 
       var result = match.Groups["email"]; 
      } 

請記住,這個模式是不是100%可靠。它可以完美兼容串像

string input = "This can be recognized as email [email protected]"; 

但在串

string input = "This can't be recognized as email [email protected]@gmail.com"; 

它捕獲,儘管事實上,這封電子郵件是按規格不正確「[email protected]」。

+0

僅鏈接答案不是答案。在您的回答中包含鏈接中的相關文本,以便鏈接中斷時仍然有用。 – Tezra

相關問題