I need to find all capital letters in a string
. For example
Input : Electronics and Communication Engineering
Output: ECE
Using character sets For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter. In a character set a ^ character negates the following characters.
The regular expression [A-Z][a-z]* matches any sequence of letters that starts with an uppercase letter and is followed by zero or more lowercase letters. The special character * after the closing square bracket specifies to match zero or more occurrences of the character set.
Using isupper() method One way to achieve this is using the inbuilt string method isupper(). We should access the first letter of the string using indexing and then send the character to isupper() method, this method returns True if the given character is Capital otherwise, it returns False.
If you insist on regular expressions:
string source = @"Electronics and Communication Engineering";
string result = string.Concat(Regex
.Matches(source, "[A-Z]")
.OfType<Match>()
.Select(match => match.Value));
Linq is a (shorter) alternative:
string result = string.Concat(source.Where(c => c >= 'A' && c <= 'Z'));
Edit: If "capital letters" include all Unicode capital letters, not only English, but, say, Russian ones, regular expression will use a different pattern
string result = string.Concat(Regex
.Matches(source, @"\p{Lu}")
.OfType<Match>()
.Select(match => match.Value));
and Linq solution will use a different condition:
string result = string.Concat(source.Where(c => char.IsUpper(c)));
Linq Solution Example is here:
The extension method Where
will helps you to get the capital letters from the given string. You can use either String.Join
or String.Concat
(nicer as suggested by DmitryBychenko) for getting the final output as a string. Go through the following snippet
string inputStr = "Electronics and Communication Engineering";
string outputStr=String.Concat(inputStr.Where(x=>Char.IsUpper(x)));
Console.WriteLine(outputStr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With