javaregex

regexp pattern matching for java


I want to know the cause of regexp not working properly.

public static void run() {
    Scanner strInput = new Scanner(System.in);
    String number = strInput.nextLine();
    if(getType(number)) {
       System.out.println("good");
    } else {
       System.out.println("");
    }
}

//regExp
public static boolean getType(String word) {
    return Pattern.matches("^[a-zA-Z]*$", word); //Q1, Q2
}

for example,

Q1. Pattern.matches("^[a-zA-Z]*$", word);

Expected answer (input) : a+C+a+2+3 -> false

Q2. Pattern.matches("^[0-9|*|+|/|-]*$", word);

Expected answer (input) : 1+2/33*4 -> true , 123+333 -> true


Solution

  • So, this might be the pattern you're looking for:

    public static boolean getType(String word) {
        //Match at least 1 or more digits, *, /, +, - from beginning to the end.
        return word.matches("^[0-9*\\/+-]+$"));
        //This one is even better though. "+1", "1+", will not match
        //return word.matches("^([0-9]+[*\\/+-])+[0-9]+$"));
    }