C# Regex - Accept spaces in a string

后端 未结 3 922
予麋鹿
予麋鹿 2020-12-20 20:53

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 sp

相关标签:
3条回答
  • 2020-12-20 20:54

    You need to escape the last - character - ñ-\s is parsed like the range a-z:

    @"^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêçñ\-\s]+$"
    

    See also on Regex Storm: [a-\s] , [a\-\s]

    0 讨论(0)
  • 2020-12-20 21:01

    - denotes a character range, just as you use A-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:

    @"^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêçñ\s-]+$"
    

    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:

    @"^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêç\-\s]+$"
    

    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.

    0 讨论(0)
  • 2020-12-20 21:17

    [RegularExpression(@"^[a-zA-Z\s]+$", ErrorMessage = "Only alphabetic characters and spaces are allowed.")]

    This works

    0 讨论(0)
提交回复
热议问题