The problem is that the regular schedule should pull out the first match with a pair of brackets. That is, according to the logic of the program, it should pull out of this expression

0:SIN(20 + 20) 1:20+20 

Or another example:

 SIN(20) + SIN(SIN(30) - SIN(40)) 

should pull out:

 0:SIN(20) 1:20 

And from

 SIN(20 - SIN(40)) 

should pull out:

 0:SIN(40) 1:40 

C #, .NET 4.0!

  • 2
    Are you sure that this task should be solved through regular expressions? It may be more correct to parse this arithmetic, as the compiler does. - avp
  • Here it is obviously necessary to use "lazy" regexp. Then with it you can isolate the very first sin (x). And in the case of <pre> SIN (20) + SIN (SIN (30) - SIN (40)) </ pre>, the answer will be SIN (20), not SIN (40)). By the way, the question for clarification - what should X represent? An expression of numbers or letters as well (for example, the names of variables)? - gecube
  • SIN (X) Where X can be the same SIN (Y), or the expression Z * Z + Y or just a constant number, for example 20. - Jakeroid

2 answers 2

Try this:

  • Thanks It works :)! - Jakeroid 2:41 pm

Ah, such problems are not solved by regulars, do better on finite automata.


Yes, there is a wonderful algorithm, called "recursive descent" on it you can build a parser of mathematical expressions, with variable functions and other joys, try to google and implement. If you need and I will have time - then I will set forth an algorithm with examples

  • With a similar algorithm (my bike), I do addition, subtraction, multiplication, and division operations. I also taught the program to work with priority brackets. PS At first I wrote a bicycle, and then I learned about the algorithm :)! Advice for newbies: look better! - Jakeroid