Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET RegEx for letters and spaces

Tags:

c#

.net

regex

I am trying to create a regular expression in C# that allows only alphanumeric characters and spaces. Currently, I am trying the following:

string pattern = @"^\w+$";
Regex regex = new Regex(pattern);
if (regex.IsMatch(value) == false)
{
  // Display error
}

What am I doing wrong?

like image 796
user70192 Avatar asked Jun 01 '10 15:06

user70192


2 Answers

If you just need English, try this regex:

"^[A-Za-z ]+$"

The brackets specify a set of characters

A-Z: All capital letters

a-z: All lowercase letters

' ': Spaces

If you need unicode / internationalization, you can try this regex:

@"$[\\p{L}\\s]+$"

See https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-classes-in-regular-expressions#word-character-w

This regex will match all unicode letters and spaces, which may be more than you need, so if you just need English / basic Roman letters, the first regex will be simpler and faster to execute.

Note that for both regex I have included the ^ and $ operator which mean match at start and end. If you need to pull this out of a string and it doesn't need to be the entire string, you can remove those two operators.

like image 62
jjxtra Avatar answered Sep 28 '22 23:09

jjxtra


try this for all letter with space :

@"[\p{L} ]+$"
like image 35
Moory Pc Avatar answered Sep 29 '22 00:09

Moory Pc