Reputation: 14204
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?
Upvotes: 9
Views: 49919
Reputation: 21100
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]+$"
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.
Upvotes: 28
Reputation: 11
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";
}
Upvotes: 1
Reputation: 57149
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} ]+$";
Upvotes: 4
Reputation: 13161
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.
Upvotes: 4