2017-02-16 96 views
0

我有一個要求,使用Java正則表達式的電子郵件驗證相同,我已經在JSP上。當我從JSP複製正則表達式到JAVA時,我得到一個錯誤。但是,在JSP中它工作正常。電子郵件驗證正則表達式JAVA

if (null != email) { 
      String regex = "^([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{1,6}))?$"; 
      Pattern pattern = Pattern.compile(regex); 
      Matcher matcher = pattern.matcher(email); 
      if (!matcher.matches()) { 
       addFormException(new DropletException("Email not valid ")); 
      } 
     } 

回答

3

在java的正則表達式中,你必須使用2個反斜槓才能逃脫。即,\\

if (null != email) { 
 
      String regex = "^([_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{1,6}))?$"; 
 
      Pattern pattern = Pattern.compile(regex); 
 
      Matcher matcher = pattern.matcher(email); 
 
      if (!matcher.matches()) { 
 
       addFormException(new DropletException("Email not valid ")); 
 
      } 
 
     }

+1

工作,謝謝 – Techie

1

我假設你有你的正則表達式的問題。請使用下面的正則表達式,並嘗試運行你的代碼。你上面的代碼只有一個斜槓。

String regex = "^([_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{1,6}))?$"; 
+0

這是正確的正則表達式表達。爲什麼-1給出 – user2844511

+0

我剛剛在regex101上運行了這個函數,並以[email protected]爲例,並用你的正則表達式返回了不匹配的結果。這可能是可能的原因。但評論中的正則表達式也標記爲正確。 – user1567291

相關問題