![](/img/trans.png)
[英]Regex to validate at least two character classes (letters, number , special characters)
[英]How to check if there is at least: two letters, one number and one special character?
如何检查是否至少存在:java中的两个字母,一个数字和一个特殊字符? 这是我的代码,但我不知道我的方向是否正确。
public static boolean validarCodigo(String codigo){
//return Pattern.compile("[abc]").matcher("ba").find();
boolean ContainsAtLeastTwoLetters = Pattern.compile("[0-9]").matcher(codigo).find();
boolean tieneAlmenosDosLetras = Pattern.compile("('/[a-zA- Z]/')").matcher(codigo).find();
boolean ContainsAtLeastOneSpecialChar; = Pattern.compile ("'/[^a-zA-Z\\d]/'").matcher(codigo).find();
return ContainsAtLeastOneDigit && ContainsAtLeastTwoLetters && ContainsAtLeastOneSpecialChar;
您的正则表达式似乎有点不对,但是您做得不错。 主要的一件事是,您只检查一个数字和字母。 要解决此问题,请尝试以下正则表达式:
boolean containsAtLeastTwoLetters = Pattern.compile("[0-9].*[0-9]").matcher(codigo).find();
boolean tieneAlmenosDosLetras = Pattern.compile("[a-zA-Z].*[a-zA-Z").matcher(codigo).find();
boolean containsAtLeastOneSpecialChar = Pattern.compile ("[^a-zA-Z\\d]").matcher(codigo).find();
我自由地将变量重新格式化为Java标准实践(用LikeThis代替LikeThis)。
public static boolean validarCodigo(String codigo){
Pattern letter = Pattern.compile("[a-zA-z]");
Pattern digit = Pattern.compile("[0-9]");
// add or remove whatever special characters are permissible in your case
Pattern special = Pattern.compile ("[!@#$%&*()_+=|<>?{}\\[\\]~-]");
Matcher hasLetter = letter.matcher(codigo);
Matcher hasDigit = digit.matcher(codigo);
Matcher hasSpecial = special.matcher(codigo);
return hasLetter.find() && hasDigit.find() && hasSpecial.find();
}
您可以使用向前看来在一行中完成:
boolean hasAllThree = codigo.matches("^(?=.*[^a-zA-Z\\d])(?=(.*\\d){2})(?=(.*[a-zA-Z]){2}).*");
根据您的评论,它必须是:
因此,您的整个String需要与这些正则表达式完全匹配
^.*[0-9].*$
^.*[a-zA-Z].*[a-zA-Z].*$
^.*[^a-zA-Z\\\\d].*$
使用前瞻机制(?=...)
您可以创建一个正则表达式来检查您的字符串是否符合所有这些条件。 它看起来像:
^(?=.*[0-9])(?=.*[a-zA-Z].*[a-zA-Z])(?=.*[^a-zA-Z\\d]).*$
现在检查您的字符串是否与此正则表达式中所述完全相同,请使用matches
方法。 BTW方法还将在正则表达式的开头添加^
,在结尾添加$
,因此您不必编写它们。
您的测试代码如下所示
codigo.matches("^(?=.*[0-9])(?=.*[a-zA-Z].*[a-zA-Z])(?=.*[^a-zA-Z\\d]).*$")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.