6

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 ?

4
  • Digit and number is the same thing, please explain Commented Mar 13, 2016 at 14:08
  • What kind of string do you want to match ? Commented Mar 13, 2016 at 14:10
  • 1
    Sidenote : You should check if a variable is null before calling methods on it. Commented Mar 13, 2016 at 14:19
  • @cricket_007 Copy that, will work on that. Thanks :) Commented Mar 13, 2016 at 14:34

1 Answer 1

11

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
Sign up to request clarification or add additional context in comments.

2 Comments

Wow. thank you for replying me with a solution. I am working on it now. Will let you know how it goes :D
Thanks man for the help. Roughly getting the idea of how it works based on your examples and yes, It is working ! :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.