Home » Android » android – How to validate a string using java regex?

android – How to validate a string using java regex?

Posted by: admin June 15, 2020 Leave a comment


I want to create a program that has the capability to check a string if it is valid to be as a person’s name. But I am struggling to use regular expression for validating the string if its acceptable to be a person’s name or not. Can you help me to implement the right conditions in my code? A string will be considered as a person’s name if the following conditions are fulfilled:

  • no space before first word
  • no non-word character
  • no 2 or more consecutive spaces

I would also like to remove a space if it exists after the last word in my string. I am doing all of this just to force a user to input the right format of text that I will post soon on my JSON. That’s why everything should be validated at the first place. No problem about whitespaces because I already defined the right inputType of my EditText on my XML file.

This is the code that I tried to implement:

public boolean isFirstnameValid(String regex, String text){

        Pattern checkRegex = Pattern.compile(regex);
        Matcher regexMatcher = checkRegex.matcher(text);

        return false;
    // I returned false because, I'm still confused about what conditions should I implement.

This is the main method where my actual parameter is implemented:

    protected void onCreate(Bundle savedInstanceState) {

       // String firstname = "Kirby Aster";
       // String lastname = "Abadilla";

        et =(EditText) findViewById (R.id.editText1);
        b = (Button) findViewById (R.id.button1);
        b.setOnClickListener(new OnClickListener(){

            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                String text = et.getText().toString();
                isFirstnameValid("[A-Za-z]{1,}", text);

How to&Answers:

I don’t like the implementation of isFirstnameValid method. I think you are making it a bit complex than it should be. I would use simple String.matches to do the job, eg :

public boolean isFirstnameValid(String text){

    return text..matches("^([A-Za-z]+)(\s[A-Za-z]+)*\s?$");

The above regex meets all your conditions including allowing a space at the end. You may consider another condition of capital letter at the first of each word(regex will change a little). Then call it like :

if( isFirstnameValid(text) ){
     text = text.trim();
} else {
    // define your failing condition here

If you have any query feel free to ask.