2

I'm trying to make create a simple RegEx to test whether a string is a valid variable name (starts with a letter or _, followed by more of these or digits).

Here's what I'm trying to do:

bool match = Regex.IsMatch(@"abc",@"^[a-zA-z_][a-zA-z_0-9]*$"); // TRUE as expected
bool match = Regex.IsMatch(@"=abc",@"^[a-zA-z_][a-zA-z_0-9]*$"); // FALSE as expected
bool match = Regex.IsMatch(@"0abc",@"^[a-zA-z_][a-zA-z_0-9]*$"); // FALSE as expected

Seems to work fine. But:

bool match = Regex.IsMatch(@"^abc",@"^[a-zA-z_][a-zA-z_0-9]*$"); // TRUE. WHY?!

How is it possible that =abc does not match but ^abc does? It almost seems like the caret somehow breaks the RegEx engine. But that can't be the case. What's wrong with my RegEx?

Tushar
  • 85,780
  • 21
  • 159
  • 179
amida
  • 97
  • 3

0 Answers0