2016-03-13 45 views
2

我是新來的android開發和正則表達式。我能夠通過EditText從用戶檢索輸入,並檢查它是否爲空,然後顯示錯誤消息,如果它是空的,但我不確定如何檢查自定義正則表達式。這裏是我的代碼:如何在Android中使用自定義正則表達式驗證EditText輸入?

myInput = (EditText) findViewById(R.id.myInput); 
String myInput_Input_a = String.valueOf(myInput.getText()); 

//replace if input contains whiteSpace 
String myInput_Input = myInput_Input_a.replace(" ",""); 


    if (myInput_Input.length()==0 || myInput_Input== null){ 

       myInput.setError("Something is Missing! "); 
    }else{//Input into databsae} 

因此,即時通訊期待用戶輸入5個字符長的字符串,其中第2個字母必須是數字和最後3個字符必須是字符。那麼我該如何實現它呢?

+0

數字和數量是一樣的東西,請解釋 –

+0

你想要什麼樣的字符串相匹配? –

+1

旁註:在**調用方法之前,你應該檢查一個變量是否爲null **。 –

回答

6

一般模式來檢查輸入對正則表達式:

String regexp = "\\d{2}\\D{3}"; //your regexp here 

if (myInput_Input_a.matches(regexp)) { 
    //It's valid 
} 

上述實際的正則表達式假設你實際上意味着2號/位(同樣的事情)和3個非數字。相應地調整。

變化的正則表達式:

"\\d{2}[a-zA-Z]{3}"; //makes sure the last three are constrained to a-z (allowing both upper and lower case) 
"\\d{2}[a-z]{3}"; //makes sure the last three are constrained to a-z (allowing only lower case) 
"\\d{2}[a-zåäöA-ZÅÄÖ]{3}"; //makes sure the last three are constrained to a-z and some other non US-ASCII characters (allowing both upper and lower case) 
"\\d{2}\\p{IsAlphabetic}{3}" //last three can be any (unicode) alphabetic character not just in US-ASCII 
+0

哇。感謝您使用解決方案回覆我。我現在正在努力。請讓你知道它是怎麼回事:D – topacoBoy

+0

謝謝你的幫助。基於你的例子粗略地瞭解它是如何工作的,是的,它正在工作! :d – topacoBoy

相關問題