Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find All Capital Letter in a String - Regular Expression C# [duplicate]

I need to find all capital letters in a string. For example

Input : Electronics and Communication Engineering

Output: ECE

like image 941
Christlin Panneer Avatar asked Jun 05 '17 06:06

Christlin Panneer


People also ask

How do I find the capital letter of a regular expression?

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.

What does AZ regex mean?

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.

How to check if a word starts with an uppercase in Python?

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.


2 Answers

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)));
like image 170
Dmitry Bychenko Avatar answered Oct 17 '22 07:10

Dmitry Bychenko


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);
like image 36
sujith karivelil Avatar answered Oct 17 '22 07:10

sujith karivelil