tags:

views:

331

answers:

4

This doesn't work:

string a = "=";
Regex oper = new Regex(@"[=-*/+]");
if (oper.IsMatch(a))
   Console.WriteLine("operator");
else
   Console.WriteLine("yt");

I don't know whether I'm defining regex incorrectly or I'm missing something. Suggestions?

+7  A: 

Did you try this approach?

input == '+' // notice single quotes instead of double quotes

Are you comparing values or trying to validate input based on a known list of characters? If you are trying to validate try creating a list of characters for validation and check against that like this:

List<char> list 
    = new List<char> { '=', '+', '!', '$', '%' };

if (list.Contains(input))
{
    // you know that the input char
    // was a special character
}

If you want to use a regular expression you can do something like this:

if (Regex.IsMatch(input.ToString(), @"[=+!$%]"))
{
    // you know that the input char
    // was a special character
}
Andrew Hare
A: 

Have a look at msdn. Maybe the IsLetterOrDigit() or another funcion helps you.

tanascius
A: 
  string a = "=";
            Regex oper = new Regex(@"[=-*/+]");
            if (oper.IsMatch(a))
                Console.WriteLine("operator");
            else
                Console.WriteLine("yt");

this doesnt works.

intrinsic
+1  A: 

When inside a character class, any hyphens must be first/last, or backslash escaped. (Otherwise they are considered to be defining a range of characters, e.g. A-E matches ABCDE)

So, instead of this:

Regex oper = new Regex(@"[=-*/+]");

Do either this:

Regex oper = new Regex(@"[-=*/+]");

Or this:

Regex oper = new Regex(@"[=\-*/+]");
Peter Boughton