1

I need to write a regular expression given by the following bnf form:

<expr_num>:=<var>|<sign>|"("<expr_num>")"|<expr_num><operator_num><expr_num>

My attempt:

var=\w*
sign=+|-
operator_num=[+|-|*|/]

However, when I put in the phrase <expr_num><operator_num><expr_num> the regular expression is in infinite recursion due <expr_num> at the beginning.

My attempt: (?<expr_num>(?<var>(\[(\w+\d*)\]))|(?<sign>([\+|\-]\g<sign>)|(\d*))|(\((\g<expr_num>)\))|(\g<expr_num>[+|*|-|\/]{1}\g<expr_num>))$

Error: recursive call could loop indefinitely

How to solve this problem? How to create parser in C# for this expression?

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005

1 Answers1

0

You could do it in Regex as demonstrated here. If you need to do more than just match arithmetic expressions such as evaluating them you get into trouble with Regex. If that is the case you should take this. That article explains how to parse expression and getting the precedence right.

Uran
  • 141
  • 2
  • 12