Java 正则表达式:如何知道字符串至少包含 2 个大写字母?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18714309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:24:53  来源:igfitidea点击:

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

javaregex

提问by Ernestas Gruodis

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.

如何知道字符串至少包含 2 个大写字母?例如,这些是有效的字符串“Lazy Cat”、“NOt very lazy cat”。使用 Java 1.7。

采纳答案by hsz

Try with following regex:

尝试使用以下正则表达式:

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

or

或者

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

回答by Pratik Tari

Try this:

尝试这个:

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

回答by Jules G.M.

This regex works.

这个正则表达式有效。

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

回答by Maroun

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..
}

回答by Suresh Atta

You have somany regex answers right now,

你现在有很多正则表达式的答案,

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

如果你不想使用**regex**,就去吧,

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