Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
480 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you just need English, try this regex:

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

The brackets specify a set of characters

0-9: All digits

A-Z: All capital letters

a-z: All lowercase letters

' ': Spaces

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

"^[\w ]+$"

This regex will match all unicode letters and numbers and space, which may be more than you need, so if you just need English or basic Roman characters, 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...