Reputation: 1347
I tried to check if a string Name contains letters, numbers, and underscore character with the following code without success, any idea of what I miss here?
var regex = new Regex(@"^[a-zA-Z0-9]+$^\w+$");
if (regex.IsMatch(Name) )
....
in addtion when I tried with the following code, I got a parsing error
"^[a-zA-Z0-9\_]+$" - Unrecognized escape sequence \_.
Var regex = new Regex(@"^[a-zA-Z0-9\_]+$");
Upvotes: 2
Views: 7290
Reputation: 28403
Try this regex
^[a-zA-Z0-9_-]$
You can match name with length also by this regex
^[a-zA-Z0-9_-]{m,n}$
Where
m is the start index
n is the end index
Take a look at here
Upvotes: 1
Reputation: 71538
The regex should be:
@"^[a-zA-Z0-9_]+$"
You don't need to escape the underscore. You can also use the Regex.Ignorecase option, which would allow you to use @"^[a-z0-9_]+$"
just as well.
Upvotes: 6