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
^[a-zA-Z]*$
Match at least 0 or more of lowercase/uppercase letters from beginning to the end. a+C+a+2+3
does not satisfy those requirements but an empty string does.^[0-9|*|+|/|-]*$
Match at least 0 or more of digits, *
, +
, /
or -
from beginning to the end; thus will match 1+2/33*4
and an empty string too.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]+$"));
}