Jamie
Jamie

Reputation: 1657

Regex Not Matching as Expected in C#

I'm using the following code:

string tile = "a1";
Regex regex= new Regex(@"/([a-z])(\d{1,2})/i");
if (regex.Match(tile).Success) Console.WriteLine("Found a match.");
    else Console.WriteLine("No match.");

and the console returns "No match." The regex itself seems fine to me, but I'm probably missing something simple. Any help would be appreciated.

Upvotes: 1

Views: 152

Answers (3)

user47589
user47589

Reputation:

Regex regex = new Regex(@"([a-z])(\d{1,2})");

I'm not sure why you have a leading / and a trailing /i. Those match the characters / and /i, respectively.

Upvotes: 0

cwharris
cwharris

Reputation: 18125

Try this:

string tile = "a1";
Regex regex = new Regex(@"([a-z])(\d{1,2})", RegexOptions.IgnoreCase);
if (regex.Match(tile).Success) Console.WriteLine("Found a match.");
    else Console.WriteLine("No match.");

Upvotes: 2

canon
canon

Reputation: 41715

You're using some javascript regex delineators. Try:

Regex regex = new Regex(@"([a-z])(\d{1,2})", RegexOptions.IgnoreCase);

Then you'll probably want to use IsMatch():

if(regex.IsMatch(tile))
{
    // ...
}

Upvotes: 5

Related Questions