Validating parts of a string input to make sure letters or numbers are input for certain indexes

Stupid title aside, I’m having trouble validating that the value “MBA222” is not allowed when inputted and values like “MB2222” are. That is to say I’m unsure of how to insure the first two characters of the String are letters and the next four are numbers. Am I perhaps using the wrong method?

public static String getValidMembership(String aMember){

    while(isValidMembership(aMember) == false){
        aMember = JOptionPane.showInputDialog("Please enter Membership Number");
    }
    return aMember;
}

private static boolean isValidMembership(String aMember){
    boolean result = false;

    //TODO add your code here
    try{
        if(!aMember.substring(0,1).contains("[a-zA-Z]+") &&
            !aMember.substring(2,5).contains("[0-9]+")&&
            aMember.length() != 6){
            result = false;

        }
        else{
            result = true; 
        }
    }catch(Exception e){
        result = false; 
    }
    return result;
}

Answer

All you need is a single regex:

public static boolean isValidMembership(String aMember) {
    return Pattern.matches("^[a-zA-Z]{2}\d{4}$", aMember);
}

I would recommend reading the Javadoc for the Pattern class which provides a lot of details of how to use regexes.

Leave a Reply

Your email address will not be published. Required fields are marked *