Detect if a string contains uppercase characters

C#RegexString

C# Problem Overview


Is there an alternative to using a regular expression to detect if a string contains uppercase characters? Currently I'm using the following regular expression:

Regex.IsMatch(fullUri, "[A-Z]") 

It works fine but I often hear the old adage "If you're using regular expressions you now have two problems".

C# Solutions


Solution 1 - C#

You can use LINQ:

fullUri.Any(char.IsUpper);

Solution 2 - C#

RegEx seems to be overkill:

bool containsAtLeastOneUppercase = fullUri.Any(char.IsUpper);

Solution 3 - C#

You could probably also do (if you want something that will work in .NET 1.0 :):

bool hasUpperCase = !fullUri.ToLower().Equals(fullUri);

Although a regex this simple will probably work fine

Solution 4 - C#

Use Linq!

fullUri.Any(c=> char.IsUpper(c));

Solution 5 - C#

Your regex will only find ASCII uppercase letters. Conveniently, the .NET regex engine is Unicode-aware, enabling you to do

Regex.IsMatch(fullUri, @"\p{Lu}") 

although I suppose that in your case you're not expecting non-ASCII letters in your string (considering its name).

Solution 6 - C#

using for loops, not as efficient and readable as the other methods pointed out, but for starters should work and provide a comprehensive way of doing this:

int counter = 0;
for(int i=0; i< myString.Length;i++)
    {
        //if character is upper add +1 to counter
        if(char.IsUpper(chaineNonPascale[i]))
        {
            counter++;
        }
    }

Basically, you iterate over your string and check for Upper Chars, then you can add logic as to what to do with the place where there is an Upper Char. For example, insert a space where the second upper case char is found and then use the ToLower method on the whole string...

Solution 7 - C#

Using LINQ might have an impact on performance when using a large string . You can also use ASCII level comparison.

byte[] asciiBytes = Encoding.ASCII.GetBytes(fullUri);
for (int i = 0; i < asciiBytes.Length; i++)
{
	if (asciiBytes[i] > 64 && asciiBytes[i] < 91)
	{
		return true;
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionQFDevView Question on Stackoverflow
Solution 1 - C#MAVView Answer on Stackoverflow
Solution 2 - C#nvoigtView Answer on Stackoverflow
Solution 3 - C#geedubbView Answer on Stackoverflow
Solution 4 - C#AlbertoView Answer on Stackoverflow
Solution 5 - C#Tim PietzckerView Answer on Stackoverflow
Solution 6 - C#gllsView Answer on Stackoverflow
Solution 7 - C#SaiKanth_KView Answer on Stackoverflow