检查字符串中是否包含大写字母

dea*_*_Y7 0 c# regex list match .net-4.5

我目前正在学习C#和RegEx.我正在研究一个小的wordcrawler.我得到了许多单词的大清单,我可以逃避那些不适合我的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,如果单词是'McLaren'(两个大写字母),它将无法将其添加到finalList.但是如果这些单词类似于'stackOverflow'(一个大写字母但不是字符串的开头),它确实会把它作为finallist.有没有简单的方法来防止这个问题?

PS:如果有比RegEx更好的方式让我知道!

这里有些例子:

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

这些都是真的应该被接受而另一个不应该被接受.

我想要达到的是正则表达式不应该在它写成'rollsRoyce'时添加,但如果它写成'Rollsroyce'或'RollsRoyce'则应该被接受.所以我必须检查字符串中是否有大写字母.

fub*_*ubo 8

如果你想检查字符串是否包含一个大写字母 - 这将是我的方法

string sValue = "stackOverflow";
bool result = !sValue.Any(x => char.IsUpper(x));
Run Code Online (Sandbox Code Playgroud)

更新到更新的问题

string sValue = "stackOverflow";
bool result = sValue.Where(char.IsUpper).Skip(1).Any();
Run Code Online (Sandbox Code Playgroud)

这会忽略第一个字符并确定字符串的其余部分是否包含至少一个大写字母

  • 你可以简化为`bool result = sValue.Any(char.IsUpper)` (4认同)