2

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\_]+$");
user3241019
  • 811
  • 9
  • 20
Jean Tehhe
  • 1,087
  • 2
  • 17
  • 33

2 Answers2

5

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.

Jerry
  • 67,172
  • 12
  • 92
  • 128
  • Why not just @"^\w+$" – Ron Rosenfeld Feb 16 '14 at 17:15
  • @RonRosenfeld Because if there are unicode hanging around, they might match as well. `\w` is not really restricted to `[a-zA-Z0-9_]`. [Check this out](http://stackoverflow.com/a/16621778/1578604). This linked question is about `\d`, but `\d` is a subset of the `\w` class, and I'm not gonna mention all the variations of letters. – Jerry Feb 16 '14 at 17:18
  • Thanks. Didn't realize the pool of matching characters was so large. I guess most people mean [a-z0-9] when they write letters and digits, so the unicode should be excluded. And I didn't realize, until reading that link, that there were unicode digits to also be concerned about. – Ron Rosenfeld Feb 16 '14 at 17:24
  • @RonRosenfeld Yes, I didn't know either before seeing that question I linked. But I prefer keeping it strictly to the 'usual' alphabet and numbers unless explicitly mentioned otherwise. – Jerry Feb 16 '14 at 17:26
1

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

Regex Demo

Take a look at here

Vignesh Kumar A
  • 26,578
  • 11
  • 57
  • 101