开发者

.NET RegEx for letters and spaces

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
}
开发者_JS百科

What am I doing wrong?


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://learn.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.


try this for all letter with space :

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


The character class \w does not match spaces. Try replacing it with [\w ] (there's a space after the \w to match word characters and spaces. You could also replace the space with \s if you want to match any whitespace.


If, other then 0-9, a-z and A-Z, you also need to cover any accented letters like ï, é, æ, Ć or Ş then you should better use the Unicode properties \p{...} for matching, i.e. (note the space):

string pattern = @"^[\p{IsLetter}\p{IsDigit} ]+$";


This regex works great for me.

           Regex rgx = new Regex("[^a-zA-Z0-9_ ]+");
            if (rgx.IsMatch(yourstring))
            {
                var err = "Special charactes are not allowed in Tags";
            }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜