George Mauer
George Mauer

Reputation: 122212

Why doesn't this Regex work in .NET?

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?

Upvotes: 3

Views: 270

Answers (2)

David M
David M

Reputation: 72930

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

Upvotes: 3

SLaks
SLaks

Reputation: 888185

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

You should use

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

(Tested)

Upvotes: 5

Related Questions