Search code examples
c#regexdouble-byte

Allow double-byte space in Regex


I have a regex on my C# code to check if the name that end user entered is valid, my regex deny double-byte characters like double-byte space.

The double-byte space like the space between quotation “ “ .

My regex: @"^[\p{L}\p{M}\p{N}' \.\-]+$".

I'm already tried to edit this regex to accept double-byte space, but I did not reach meaningful result.

So please if any one can edit this regex to accept double-byte space, I will be thankful for him.


Solution

  • You need to replace a literal space with a pattern that matches any horizontal Unicode whitespace and in .NET regex, it can be achieved with \p{Zs}.

    @"^[\p{L}\p{M}\p{N}\p{Zs}'.-]+$"
    

    See the regex demo.

    Note this pattern does not match a TAB char. If you need to match a TAB, too, you just need to add it,

    @"^[\p{L}\p{M}\p{N}\p{Zs}\t'.-]+$"
    

    Note you do not need to escape . and - in this regex. . inside square brackets is not any special regex metacharacter and - is not special when it is placed at the end of the character class.