使用正则表达式检查字符串是否至少有两个数字

Jac*_*ack 4 java regex

在深入研究堆栈溢出后,我发现了一些代码来检查字符串是否为字母数字且超过 8 个字符。它工作得很好。现在,如果它包含至少 2 个数字,我该如何让它返回 true?我想我必须在\d{2}某处添加。

String pattern = "^[a-zA-Z0-9]*$";

if (s.matches(pattern) && s.length() >= 8){
    return true;
}
return false;
Run Code Online (Sandbox Code Playgroud)

Avi*_*Raj 5

您不需要单独的 if 条件。一个正则表达式将为您完成所有工作。

String pattern = "^(?=.*?\\d.*\\d)[a-zA-Z0-9]{8,}$";
Run Code Online (Sandbox Code Playgroud)