tags:

views:

115

answers:

2

Hello,

How should like a regex which validates the name and surname, so that each word starts with a capital letter? this does not work: @"[^A-Z]?[a-z]*"

Thanks

+1  A: 

Try this:

[A-Z][a-z]*

Note that this is, however, not a good way to validate names. Depending on the locale, non-ASCII UTF8 characters may be used. Also, not all names start with an uppercase letter. The following names exist in the real world:

Martha de Lange Norton
Marcél du Toit

Hence, this is a little better - it just makes sure that each character is a valid letter:

\p{L}+

That said, the best way to do this may depend on the implementation of the regular expression engine, so we'd need to know the language and/or regex library that you are using.

Edit based on your answer: If you need to parse both fields at the same time, try this:

^[A-Z][a-z]*\s[A-Z][a-z]*$
knipknap
@"" defines a string literal in C#, eliminating the need to do double escaping. Helpful for regexes. (Although it's superfluous for the OP's regex since there are no special characters.)
Alison R.
So i have:[RegexValidator(@"[A-Z][a-z]*", MessageTemplate = "Name must be valid!", Ruleset="validate_name")]And the test passes with "laddf Ghu" for example, which is not correct (laddf does not start with capital letter).
qwerty
A: 

That states that it does NOT start with one or more capitals. ^ within the character class means negation... [^A-Z] means everything except capitals. Outside of the brackets, it means 'beginning of the string', which I assume is what you intended. You want this:

^[A-Z]?[a-z]* for one or more of capitals at the beginning, or

^[A-Z][a-z]* for exactly one capital, or

^[A-Z][A-Za-z]* for capitals anywhere, but definitely one at the beginning.

Ipsquiggle
I would go with the last one since McGregor is a legal name. But don't forget about O'Reilly.
klausbyskov