简体   繁体   English

如何计算数字或字符匹配的模式?

[英]How to count number or characters match the pattern?

Here is my function that checks whether the string is alpha/numeric 这是我的功能,用于检查字符串是否为字母/数字

public boolean bpIsAlphaNumeric(String s){
    String pattern= "^[a-zA-Z0-9]*$";
    if(s.matches(pattern)){
        return true;
    }
    return false; 
}

It works perfect. 完美的作品。 Now I need (using same method/pattern) to check that String s contains at least xxx alpha/numeric characters. 现在,我需要(使用相同的方法/模式)来检查String至少包含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

This is mostly from @f1sh's answer: 这主要来自@ f1sh的答案:

String regex = "([^a-zA-Z0-9]*[a-zA-Z0-9]){4,}"

It accepts ((non-alpha)* (alpha) at least 4 times). 它接受((非alpha)*(alpha)至少4次)。

I am not sure if the above pattern works. 我不确定上述模式是否有效。 In case it does not, you can try this one as well: 如果没有,您也可以尝试以下方法:

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

Use curly braces ({}) when you want to be very specific about the number of occurrences an operator or subexpression must match in the source string. 如果您想非常具体地说明运算符或子表达式在源字符串中必须匹配的出现次数,请使用大括号({})。 Curly braces and their contents are known as interval expressions. 花括号和它们的内容被称为区间表达式。 You can specify an exact number or a range. 您可以指定一个确切的数字或范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM