查找字符串中的所有大写字母 - 正则表达式C#

时间:2017-06-05 06:46:21

标签: c# .net regex string

我需要在string中找到所有大写字母。例如

输入Electronics and Communication Engineering

输出ECE

4 个答案:

答案 0 :(得分:5)

如果你坚持正则表达式

 string source = @"Electronics and Communication Engineering";

 string result = string.Concat(Regex
   .Matches(source, "[A-Z]")
   .OfType<Match>()
   .Select(match => match.Value));

Linq 是一个(更短的)替代方案:

 string result = string.Concat(source.Where(c => c >= 'A' && c <= 'Z'));

答案 1 :(得分:2)

使用LINQ:

string text = "Electronics and Communication Engineering";
var capitalLetters = text.Where(c => char.IsUpper(c)).ToArray();

答案 2 :(得分:2)

Linq解决方案Example is here

扩展方法Where将帮助您从给定字符串中获取大写字母。您可以使用String.JoinString.Concat(更好,如 DmitryBychenko 所示)来获得最终输出为字符串。浏览以下代码段

string inputStr = "Electronics and Communication Engineering";
string outputStr=String.Concat(inputStr.Where(x=>Char.IsUpper(x)));
Console.WriteLine(outputStr);

答案 3 :(得分:0)

var s = "Electronics and Communication Engineering";

result = string.Concat(s.Select(c => char.IsUpper(c) ? c.ToString() : ""))
            .TrimStart();