Aaron
Aaron

Reputation: 4480

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);
}

Upvotes: 0

Views: 1977

Answers (1)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

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:

^\p{Lu}\p{Ll}*$

If we simplify the code a bit we get:

public bool VerifyName(string name)
    => Regex.IsMatch(name, @"^\p{Lu}\p{Ll}*$");

Upvotes: 5

Related Questions