2

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

2

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • I found a problem in my regex that the regex accept the name that contains spaces only, how can I solve this? – Mahmoud Abdeen Mar 22 '21 at 11:46
  • @MahmoudAbdeen `@"^(?!\s+$)[\p{L}\p{M}\p{N}\p{Zs}\t'.-]+$"` – Wiktor Stribiżew Mar 22 '21 at 11:47
  • At first thank you so much, your edit solve the name that contains spaces only, but when I tried to check the name that contains double-byte spaces only, the regex still accept it. – Mahmoud Abdeen Mar 22 '21 at 11:52
  • @MahmoudAbdeen It is [impossible](http://regexstorm.net/tester?p=%5e%28%3f!%5cs%2b%24%29%5b%5cp%7bL%7d%5cp%7bM%7d%5cp%7bN%7d%5cp%7bZs%7d%27.-%5d%2b%24&i=%e3%80%80%e3%80%80%e3%80%80%e3%80%80%e3%80%80) – Wiktor Stribiżew Mar 22 '21 at 11:53
  • Im check the regex here https://regex101.com/r/fx0UW8/1/ and its return the double-byte spaces name as match – Mahmoud Abdeen Mar 22 '21 at 11:57
  • @MahmoudAbdeen regex101 does not support .NET regex. Do not rely on regex101 when you check a regex that you intend to use with .NET regex engine. – Wiktor Stribiżew Mar 22 '21 at 11:58
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/230226/discussion-between-mahmoud-abdeen-and-wiktor-stribizew). – Mahmoud Abdeen Mar 22 '21 at 11:58