检查大写字母是否在字符串内

检查大写字母是否在字符串内

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

问题描述

我目前正在学习 C# 和 RegEx.我正在开发一个小型的 wordcrawler.我得到了一个包含许多单词的大列表,其中我将那些不适合我的 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.

推荐答案

有一个非常简单的解决方案,无需正则表达式或 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
}

只是检查字符串是否等于它的小写自身.

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

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

08-15 11:22