![](/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.