I have an application which needs some verifications for some fields. One of them is for a last name which can be composed of 2 words. In my regex, I have to accept these spaces so I tried a lot of things but I did'nt find any solution.
Here is my regex :
@"^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêçñ-\s]+$"
The \s
are normally for the spaces but it does not work and I got this error message :
parsing "^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêçñ-\s]+$" - Cannot include class \s in character range.
ANy idea guys?
Best Answer
-
denotes a character range, just as you useA-Z
to describe any character between A and Z. Your regex usesñ-\s
which the engine tries to interpret as any character between ñ and \s -- and then notices, that\s
doesn't make a whole lot of sense there, because\s
itself is only an abbreviation for any whitespace character.That's where the error comes from.
To get rid of this, you should always put
-
at the end of your character class, if you want to include the-
literal character:This way, the engine knows that
\s-
is not a character range, but the two characters\s
and-
seperately.The other way is to escape the
-
character:So now the engine interprets
ñ\-\s
not as a character range, but as any of the charactersñ
,-
or\s
. Personally, though I always try to avoid escaping as often as possible, because IMHO it clutters up and needlessly stretches the expression in length.