我对 java 的正则表达式模式匹配有疑问

I have a question about regexp pattern matching for java

我想知道正则表达式不能正常工作的原因。

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
}

例如,

Q1。 Pattern.matches("^[a-zA-Z]*$", word); 期望的答案(输入):a+C+a+2+3 -> false

Q2。 Pattern.matches("^[0-9|*|+|/|-]*$", word); 期望的答案(输入):1+2/33*4 -> true , 123+333 -> true

对不起, 因为我是外国人所以英语不好请理解..

  • ^[a-zA-Z]*$ 从头到尾匹配至少 0 个或多个 lowercase/uppercase 字母 a+C+a+2+3 不满足这些要求,但空字符串可以。
  • ^[0-9|*|+|/|-]*$ 匹配至少 0 个或更多的 数字*+/- 从头到尾;因此也将匹配 1+2/33*4 和一个空字符串。

所以,这可能是您正在寻找的模式:

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]+$"));
}