Reputation: 338
I know this statement should return false as expected
Regex.IsMatch("+", @"[a-zA-Z0-9]")
but why these statements matches although they shouldn't (from my understanding)
Regex.IsMatch("C++", @"[a-zA-Z0-9]")
Regex.IsMatch("C++", @"[a-zA-Z0-9]+")
Upvotes: 0
Views: 904
Reputation: 700192
Those are matches because you don't match the entire string. They will match the C
in C++
.
Use ^
and $
to match the beginning and end of the string:
bool onlyAlphaNumeric = Regex.IsMatch("C++", @"^[a-zA-Z0-9]+$"); // will be false
Upvotes: 4