简体   繁体   中英

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

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}*$");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM