Search code examples
javachardigitletter

Check if a string match a defined pattern


I am working on an assignment right now where I have to enter an input in "ABC123456" format entry and see if it is valid or not. I don't understand how to check each character if it is a number or letter. Here is what I have so far:

import java.util.Scanner;
public class NetID {


    public static void main(String[] args) {    
        Scanner input = new Scanner (System.in);
        String userInput, char0thru2, char3thru8, uppercase, netID;

        System.out.println("Please enter the NetID to verify:");
        userInput = input.nextLine();

        if (userInput.length() != 9) {
            System.out.println("Your NetID needs to be 9 characters long, it needs to be in this format: ABC123456");
        }   
        if (userInput.length() == 9){
            char0thru2 = userInput.substring(0, 3);
            char3thru8 = userInput.substring(3, 9);
            uppercase = char0thru2.toUpperCase();
        }
    }
}

Solution

  • Just use a pattern:

    String userInput = "ABC133456";
    
        if(!Pattern.matches("[A-Z]{3}[0-9]{6}", userInput))
             System.out.println("Your NetID needs to be 9 characters long, it needs to be in this format: ABC123456");
        else
             System.out.println("Ok!");