tags:

views:

86

answers:

2

I want a regex that will verify that a string begins with a letter followed by some letters, numbers, or underscores. According to my EditPadPro regex parser the following test should pass. But it does not.

Regex.IsMatch("Class1_1", @"^\w[\w|\d|_]*$").ShouldBeTrue();

What am I missing?

+5  A: 

Your regex works, but doesn't do what you think it does.

You should use

Regex.IsMatch("Class1_1", @"^[A-Za-z]\w*$")

(Tested)

SLaks
Alternately, "^\w[\w\d_]*$", but, as has been pointed out by David M, \w includes \d and _ anyway, so actually "^[a-zA-Z]\w+$"
Zarigani
+3  A: 

\w includes \d and underscore - even if your test passes, the Regex won't be testing what you want it to!

David M
Regex.IsMatch("Class1_1", @"^\w+$") doesn't work. Any comment on why?
George Mauer
Possibly your globalization settings - that expression matches on my machine.
Eamon Nerbonne