Reputation: 43
There is a really simple answer to this, I know there is. But I cannot get my head around it. Its a console application you enter a word "password" and it will tell me whether it matches my regular expression, as you can properly gather.
Basically I want to know why this wont work:
static void Main(string[] args)
{
Regex regularExpression = new Regex("/^[a-z0-9_-]{3,16}$/");
Console.Write("Enter password: ");
string password = Console.ReadLine();
if (Regex.IsMatch(password, regularExpression))
Console.WriteLine("Input matches regular expression");
else
Console.WriteLine("Input DOES NOT match regular expression");
Console.ReadKey();
}
I'm sure it's something to do with the Regex.IsMatch
method not being able to convert string to int.
Upvotes: 0
Views: 1698
Reputation: 93026
Because you are using the static method isMatch
and are giving a regex object, where it expects a regex as string, see the Regex class.
And additionally you don't need regex delimiters in .net.
Use this:
static void Main(string[] args) {
Regex regularExpression = new Regex(@"^[a-z0-9_-]{3,16}$");
Console.Write("Enter password: ");
string password = Console.ReadLine();
if (regularExpression.IsMatch(password))
Console.WriteLine("Input matches regular expression");
else
Console.WriteLine("Input DOES NOT match regular expression");
Console.ReadKey();
}
Upvotes: 2
Reputation: 13450
Regex regularExpression = new Regex("/^[a-z0-9_-]{3,16}$/");
/
is symbol, replace them to string empty => @"^[a-z0-9_-]{3,16}$"
Upvotes: 0