Regular expressions in C #

0

I am developing an expression evaluator, and I have the following code to check that I do not know about the following combination of characters

for example:

* - a multiplication followed by two signs of subtraction

* / a multiplication followed by a division

* + a multiplication followed by a sum

this is the code that works correctly

private static Boolean EvaluaExprMat(String expr)
  {
    for(int pos = 0; pos < expr.Length - 1; pos++)
    {
      char car1 = expr[pos];  
      char car2 = expr[pos + 1]; 

      if (car1 == '+' || car1 == '-' || car1 == '*' || car1 == '/' || car1 == '^')
        if (car2 == '+' || car2 == '*' || car2 == '/' || car2 == '^')
          return true;
    }

    for (int pos = 0; pos < expr.Length - 2; pos++)
    {
      char car1 = expr[pos];  
      char car2 = expr[pos + 1];
      char car3 = expr[pos + 2];


      if (car1 == '+' || car1 == '-' || car1 == '*' || car1 == '/' || car1 == '^')
        if (car2 == '+' || car2 == '-' || car2 == '*' || car2 == '/' || car2 == '^')
          if (car3 == '+' || car3 == '-' || car3 == '*' || car3 == '/' || car3 == '^')
            return true;
    }

How could I run these evaluations using regular expressions? can someone help me a bit with this issue, I want to reduce the code using that kind of tool. Thanks

    
asked by Gloria 23.06.2018 в 19:28
source

1 answer

0

Hi Gloria, I enclose the solution you request:

        private static Boolean EvaluaExprMat(String expr)
    {
        String filtro = @"(\*\-\-)|(\*\/)|(\*\+) ";
        Regex rgx = new Regex(filtro, RegexOptions.IgnoreCase);
        if (rgx.IsMatch(expr))
            return true;
        else
            return false;

    }

The regular expression evaluates your 3 requirements and returns true if any is true. Each requirement is delimited by the () and each sign is preceded by a "\" to use it as a literal since for example the sign "*" has its own meaning within the world of regular expressions

On this page link you can both test the regular expressions you do online and learn how to do them, even if the explanation comes in English

    
answered by 24.06.2018 / 02:36
source