使用正则表达式检查字符串至少有两个数字 [英] Using regex to check is string has at least two numbers

查看:474
本文介绍了使用正则表达式检查字符串至少有两个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在挖掘堆栈溢出后,我发现了一些代码,用于检查字符串是否为字母数字,且长度为8个字符。它很棒。现在,如果它包含至少2个数字,我该如何使它返回true?我想我必须在某处添加 \d {2}

After digging around on stack overflow, I found some code which checks if the string is alphanumeric and longer that 8 chars. It works great. Now how do I make it return true if it contains at least 2 numbers? I think I have to add \d{2} somewhere.

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

if (s.matches(pattern) && s.length() >= 8){
    return true;
}
return false;


推荐答案

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

You don't need a separate if condition. A single regex will do all for you.

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

这篇关于使用正则表达式检查字符串至少有两个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆