2011-08-17 40 views
0

我想設置電子郵件輸入的定期驗證。使用正則表達式進行Java驗證

我有這樣的Java類,它確實驗證:

public class EmailValidator implements Validator { 

@Override 
public void validate(FacesContext facesContext, 
UIComponent uIComponent, Object value) throws ValidatorException { 

//Get the component's contents and cast it to a String 
String enteredEmail = (String)value; 

//Set the email pattern string 
Pattern p = Pattern.compile("[email protected]+\\.[a-z]+"); 

//Match the given string with the pattern 
Matcher m = p.matcher(enteredEmail); 

//Check whether match is found 
boolean matchFound = m.matches(); 

if (!matchFound) { 
    FacesMessage message = new FacesMessage(); 
    message.setDetail("Email not valid - The email must be in the format [email protected]"); 
    message.setSummary("Email not valid - The email must be in the format [email protected]"); 
    message.setSeverity(FacesMessage.SEVERITY_ERROR); 
    throw new ValidatorException(message); 
} 
} 
} 

有這個代碼默認模式。但是,我試圖用另一種模式替換它。 (?:(?:(?:[^ @,「[] \ x5c \ x00- \ x20 \ x7f- \ xff。] | \ x5c(?= [@,」[ ](?:[^ @,「[] \ x5c \ x00- \ x20 \ x7f- \ xff。] |(?< = \ x5c)[@ 「[] \ x5c \ x00- \ X20 \ x7f- \ XFF] | \ x5c(?= [@,」[] \ x5c \ x00- \ X20 \ x7f- \ XFF])|。?(= [^ 。])){1,62}(?:[^ @,「[] \ x5c \ x00- \ x20 \ x7f- \ xff。] |(?< = \ x5c)[@,」[] \ x5c \ x00- \ X20 \ x7f- \ XFF])| [^ @, 「[] \ x5c \ x00- \ X20 \ x7f- \ XFF] {1,2})|。」(?:[^「] |( (α:[α-ZA-Z0-9] [a-zA-Z0-9-] { 1,61} [A-ZA-Z0-9] | [A-ZA-Z0-9])+(?: XN - [A-ZA-Z0-9] + |。?。?。[A- ZA-Z] {2,6-})| [(:[0-1?] \ d \ d | 2 [0-4] \ d | 25 [0-5])(:???(?: [0-1]?\ d?\ d | 2 [0-4] \ d | 25 [0-5])){3}])$/

我知道可以使用這種模式嗎?或者我需要把一些括號等,使其工作?我現在收到非法開始的表達錯誤。

+0

你在使用什麼模式? – 8vius

回答

0

我確定可以使用正則表達式可以使用,但是您必須正確地將其插入代碼中。但是,檢查電子郵件是否有效的最好方法是發送一封電子郵件。 Here是一個用正則表達式進行電子郵件驗證的好網站,當然你也可以在這個網站上搜索很多類似的問題。

0

如果你正在嘗試做的電子郵件驗證這種模式的工作原理和短得多^[a-z0-9!#$%&'*+/=?^_ {|}〜 - ] +(?:\。[A-Z0-9#$%&「* +/=!?^_ {|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$

我使用Java的正則表達式util包(java.util.regex.*),這裏的一對,並在Java正則表達式在一般的文檔:您可以使用正則表達式(或任何你想

http://java.sun.com/developer/technicalArticles/releases/1.4regex/

+0

所以我所要做的就是逃避所有/和\?如果我只逃脫「/」它不起作用 – RUiHAO

+0

我修改了正則表達式爲java工作,只需按照我給你的文檔,你應該能夠做到這一點沒有問題。 – 8vius

0

, ),但請記住在java字符串中跳出反斜槓\(by輸入兩個\\)。

Here是一個頁面,可以讓你將正則表達式字符串轉換爲Java字符串,也就是說,它爲你完成所有爲怪異字符轉義的行爲......(頁面似乎現在正在向下移動,但它昨天正在工作,所以只是稍後檢查...)

-2

您可以使用此表達式進行電子郵件驗證「[A-Za-z] + @ + [A-Za-z] + \。+ [A-Za-z] {2,4} + $」 這樣做要簡單得多。

+0

該正則表達式不會驗證所有有效的電子郵件地址。 – CanSpice

0

試試這個,請和我一起工作很好。

String expressionForEmail = "^[\\w\\.-][email protected]([\\w\\-]+\\.)+[a-zA-Z]{2,4}$";