Regex expressions in C#

Viewed 103

I am trying to make an name validation Regex expression, to check, if name is passed in correct format. It needs to be in format like - 'John', 'Sarah', so, no whitespaces allowed, no other characters allowed and no numbers allowed. Also, the first letter has to be capital, and all other letters following has to be non capital letters.

I have tried writing some regex expressions and checking them on regexr, but expression that works there, does not work correctly in C#

Can someone share solution to exclude any other character, that IS NOT a letter?

For me it seems, that there are some differences between regex used on regexr and regex used in C# and thats why the expression that works on regexr, does not work in C#

Thank you in advance! :)

EDIT: For example: Expression is - ([A-Z]{1}[a-z]*)\w+. In regexr, it has to be 1st capital letter, then any other letter, all whitespaces or other characters excluded. When I copy this in my C# project, it still allows to write whitespaces or other symbols like . ; , etc.

EDIT2: C# implementation looks like this:

            string name = nameCapitalLetterCheck_textBox.Text.ToString();
            string nameFormat = @"([A-Z]{1}[a-z]*)\w+";
            if (Regex.IsMatch(name,nameFormat))
            {
                nameCapitalLetterCheck_result.Text = "OK";
                nameCapitalLetterCheck_result.Foreground = green;
                nameCapital_hint.Visibility = Visibility.Hidden;
            }
            else
            {
                nameCapitalLetterCheck_result.Text = "Error";
                nameCapitalLetterCheck_result.Foreground = red;
                nameCapital_hint.Visibility = Visibility.Visible;
            }
1 Answers

Use

^\p{Lu}\p{Ll}+\z

See proof

Explanation

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  \p{Lu}                    any uppercase character
--------------------------------------------------------------------------------
  \p{Ll}+                  any lowercase character (1 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  \z                       the end of the string
Related