簡體   English   中英

如何在Android中使用自定義正則表達式驗證EditText輸入?

[英]How to validate EditText input with a custom regex in Android?

我是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個字符必須是字符。 那我該如何實現呢?

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM