How to check string using java regex?

I want to create a program that has the ability to check a string if it is valid as a person’s name. But I'm struggling to use a regular expression to validate a string if it is acceptable for the person’s name or not. Can you help me implement the correct conditions in my code? The string will be considered the name of the person if the following conditions are true:

  • space before the first word
  • character without word
  • no 2 or more consecutive spaces

I would also like to remove the space if it exists after the last word in my line. I am doing all this simply to get the user to enter the correct text format, which I will publish shortly in my JSON. That is why everything must be confirmed first. There is no problem with spaces, because I already defined the correct inputType of my EditText in my XML file.

This is the code 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 for implementing my actual parameter:

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

        });
    }
+4
source share
1 answer

isFirstnameValid. , , . String.matches , :

public boolean isFirstnameValid(String text){

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

, . ( ). :

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

- , .

+5

All Articles