Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a string using java regex?

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);

        while(regexMatcher.find()){
            if(regexMatcher.group().length()!=0){
                Log.e("searched",regexMatcher.group().trim());
            }
        }
        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:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

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

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

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

        });
    }
like image 236
KirbyAbadilla Avatar asked Oct 29 '14 03:10

KirbyAbadilla


1 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.

like image 149
blackSmith Avatar answered Oct 19 '22 22:10

blackSmith