简体   繁体   中英

Regex: how to know that string contains at least 2 upper case letters?

How to know that string contains at least 2 upper case letters? For example these are valid strings "Lazy Cat", "NOt very lazy cat". Working with Java 1.7.

这个正则表达式有效。

string.matches(".*[A-Z].*[A-Z].*")

Try with following regex:

"^(.*?[A-Z]){2,}.*$"

or

"^(.*?[A-Z]){2,}"

I'll now show you a full solution, I'll guide you.

If you don't want to use regex, you can simply loop on the String, chat by char and check whether it's an upper case:

for (int i=0;i<myStr.length();i++)
{
     //as @sanbhat suggested, use Character#isUpperCase on each character..
}

You have somany regex answers right now,

Go for it if you don't want to use **regex** ,

String someString = "abcDS";
int upperCount = 0;
for (char c : someString.toCharArray()) {
    if (Character.isUpperCase(c)) {
        upperFound++;
    }
}
// upperFound  here weather >2 or not

试试这个:

string.matches("[A-Z]+.*[A-Z]+");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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