user690069
user690069

Reputation: 338

regex ismatch logic with special character

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

Answers (1)

Guffa
Guffa

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

Related Questions