首页 > 解决方案 > 我有一个关于 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

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

标签: javaregexpattern-matching

解决方案


  • ^[a-zA-Z]*$从头到尾 匹配至少 0 个或多个小写/大写字母。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]+$"));
}

推荐阅读