检查字符串中是否包含大写字母 [英] Check if an uppercase Letter is inside a string

查看:914
本文介绍了检查字符串中是否包含大写字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习C#和RegEx.我正在做一个小型的爬虫器.我得到了很多单词的大清单,在其中我逃避了那些不适合我的RegEx的单词.

I am currently learning C# and RegEx. I am working on a small wordcrawler. I get a big list of many words where I escape those which don't fit to my RegEx.

这是我的代码:

var WordRegex = new Regex("^[a-zA-Z]{4,}$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
var secondRegex = new Regex("([A-Z]{1})");

var words = new List<string>();
var finalList = new List<string>();

foreach (var word in words)
{
    if (WordRegex.IsMatch(word) && secondRegex.Matches(word).Count == 1 || secondRegex.Matches(word).Count == 0)
    {
         finalList.Add(word);
    }
}

因此,如果单词是"McLaren"(两个大写字母),则此方法会很好地工作,它不会将其添加到finalList.但是,如果这些单词类似于"stackOverflow"(一个大写字母,但不在字符串开头),它会将其带入最终列表.有什么简单的方法可以防止此问题?

So this works fine if the word is 'McLaren' (two uppercase letters) it won't add it to finalList. But if the words is something like 'stackOverflow' (one uppercase letter but not at start of string), it does take it to finallist. Is there any simple way to prevent this problem?

PS:如果有比RegEx更好的方法,请告诉我!

PS: if there is any better way than RegEx let me know!

以下是一些示例:

("McLaren");//false
("Nissan");//true
("BMW");//false
("Subaru");//true
("Maserati");//true
("Mercedes Benz");//false
("Volkswagen");//true
("audi");//true
("Alfa Romeo");//false
("rollsRoyce");//false
("drive");//true

这些为true的应该被接受,而另一个不应该被接受.

These with true should be accepted and the other shouldn't be accepted.

我想知道的是,当正则表达式写成"rollsRoyce"时,不应该添加正则表达式,但是如果它写成"Rollsroyce"或"RollsRoyce",则应接受该正则表达式.因此,我必须检查字符串中是否有大写字母.

What I want to reach is that the regex shouldnt add when its written like this'rollsRoyce' but if it's written like 'Rollsroyce' or 'RollsRoyce' it should be accepted. So I have to check if there are uppercase letters inside the string.

推荐答案

没有regex或linq,有一个非常简单的解决方案:

There is a very easy solution without regex or linq:

bool hasUppercase = !str.equals(str.toLowerCase());

现在您可以轻松检查:

if(!hasUppercase) {
    // no uppercase letter
}

else {
    // there is an uppercase letter
}

只需检查字符串是否等于其小写的self.

Just checking if the string is equal to its lowercased self.

这篇关于检查字符串中是否包含大写字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆