【问题标题】:I have a question about regexp pattern matching for java我对java的正则表达式模式匹配有疑问
【发布时间】:2021-08-30 21:49:44
【问题描述】:

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

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
}

例如,

第一季度。 Pattern.matches("^[a-zA-Z]*$", word); 想要的答案(输入):a+C+a+2+3 -> false

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

对不起,我是外国人,英文不好,请谅解。

【问题讨论】:

    标签: java regex pattern-matching


    【解决方案1】:
    • ^[a-zA-Z]*$ 从头到尾匹配至少 0 个或多个小写/大写 字母a+C+a+2+3 不满足这些要求,但空字符串可以。
    • ^[0-9|*|+|/|-]*$ 从头到尾匹配至少 0 个或多个 digits*+/-;因此将匹配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]+$"));
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多