Aaron Aaron - 1 year ago 130
C# Question

C# Regex first letter capital the rest lower case

I am trying to write a regex that returns true if the first letter is capitalized and the rest are lower case. However, the method I wrote always returns false. What is wrong with my regex and what changes should I make.
Here is my code.

public bool VerifyName(string name){
Regex rgx = new Regex("^[A-Z][a-z]+$");
return rgx.Equals(name);

Answer Source

You're using the Equals method, which will compare your string for equality with the regex object. This will never be true, it's like comparing apples and oranges. Use IsMatch instead.

And you could also improve the regex by adding Unicode support:


If we simplify the code a bit we get:

public bool VerifyName(string name)
    => Regex.IsMatch(name, @"^\p{Lu}\p{Ll}*$");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download