检查字符串是否由Java中的5个数字组成

Rob*_*uch -2 java regex

在Java应用程序中,我需要检查给定的字符串

  • 仅包含数字0-9和
  • 正好是五位数

我的第一次尝试是这样的:

public static void main(String[] args) {

    String testString = "000000";
    String myPattern = "\\d{5}";

    Pattern validCharacterPattern = Pattern.compile(myPattern);
    Matcher matcher = validCharacterPattern.matcher(testString);
    boolean b = matcher.find();

    if (b) System.out.println("Valid");
    else System.out.println("Invalid");

}
Run Code Online (Sandbox Code Playgroud)

然而,上述表达式也适用于例如123456.我需要改变什么?

Cru*_*her 6

为了完整起见(即使问题已完全改变)

boolean b = matcher.find();
Run Code Online (Sandbox Code Playgroud)

如果正则表达式包含在匹配字符串中的某处,则匹配.如果使用,matcher.matches您将获得预期的行为,它必须与ENTIRE字符串匹配.

或者你可以跳过编译步骤(如果这个正则表达式将被多次使用,不推荐使用.)完全只需写:

String regex = "\\d{5}";
String test = "123456";
if(test.matches(regex)){ ... };
Run Code Online (Sandbox Code Playgroud)

这基本上就是你在原始问题中所拥有的.