这是我的函数,用于检查字符串是否为字母/数字
public boolean bpIsAlphaNumeric(String s){
String pattern= "^[a-zA-Z0-9]*$";
if(s.matches(pattern)){
return true;
}
return false;
}
它完美无缺。现在我需要(使用相同的方法/模式)来检查String s是否至少包含xxx字母/数字字符。
//e.g. at least 4 characters should be alphanumeric
String "abc#DE$01%23!##^$" //true, because it contains - abcDE0123
String "!$#%#a#b&9$^$##^$" //false, because it contains only - ab9
答案 0 :(得分:0)
这主要来自@ f1sh的回答:
String regex = "([^a-zA-Z0-9]*[a-zA-Z0-9]){4,}"
它接受((非alpha)*(alpha)至少4次)。
答案 1 :(得分:0)
我不确定上述模式是否有效。如果没有,你也可以尝试这个:
public static boolean hasAtleast4AlphaNumeric(String s){
String pattern= "([a-zA-Z0-9].*){4,}.*$";
if(s.matches(pattern)){
return true;
}
return false;
}
System.out.println("Has four alphanumeric characters: " + hasAtleast4AlphaNumeric("abc#DE$01%23!##^$"));
System.out.println("Does not have four alphanumeric characters: " + hasAtleast4AlphaNumeric("!$#%#a#b&9$^$##^$"));
System.out.println("Does not have four alphanumeric characters: " + hasAtleast4AlphaNumeric("VVVV!$#%#a#b&9$^$##^$"));
Output:
Has four alphanumeric characters: true
Does not have four alphanumeric characters: false
Has four alphanumeric characters: true
如果要非常具体地说明运算符或子表达式在源字符串中必须匹配的次数,请使用花括号({})。大括号及其内容称为区间表达式。您可以指定确切的数字或范围。