I am new to android development and also regular expression. I am able to retrieve inputs from user through the EditText and check if it's empty and later display the error message if it is empty but I am not sure on how to check with a custom regex. Here's my code :
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}
So, im expecting the user to input a 5 character long string where the first 2 letters must be numbers and the last 3 characters must be characters. So how can i implement it people ?
General pattern to check input against a regular expression:
String regexp = "\\d{2}\\D{3}"; //your regexp here
if (myInput_Input_a.matches(regexp)) {
//It's valid
}
The above actual regular expression assumes you actually mean 2 numbers/digits (same thing) and 3 non-digits. Adjust accordingly.
Variations on the regexp:
"\\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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With