有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么当这个布尔值与我的正则表达式匹配时没有改变?

因此,我在Eclipse的最新版本中运行了它。出于某种原因,我和我的老师都不能理解为什么布尔值不变

This is the code

String value = null;
boolean matching = false;
String regex = "^[a-zA-Z]$";
Scanner input = new Scanner(System.in);
value = input.next();

if (value.matches(regex))
{
    matching = true;
}
else
{
    System.out.println("Name is incorrect, please try again");
}


System.out.println(matching);
System.out.println(value);

共 (1) 个答案

  1. # 1 楼答案

    通过指定正则表达式^[a-zA-Z]$,可以匹配单字母输入(例如“a”、“d”和“F”)。。。因为您输入了多字符字符串,所以它不匹配

    为了匹配长度为>=1可以在正则表达式中使用+运算符,如下所示

    ^[a-zA-Z]+$