c# - Validating recursive string structure -
i want validate string represents serialized form of expression tree. here examples want validate:
- ex 1:
(6+2)
- ex 2:
(6*(4+2))
- ex 3:
(9*(4-(7*3)))
- ex 4:
((5+2)/(9+2))
- ex 5:
(((2-1)+2)/(9+()7*2))
as can see ex 1, simple case have 2 numbers operation surrounded parenthesis. however, either number expression. these expressions can deep required.
i working in .net , wanted write regular expression validate format of string complies showed in examples. cannot figure out how write .net regular expression perform validation.
the simple case can validated following:
string testcase = "(6+2)"; string baseexpression = "([(][0-9][+-/*][0-9][)])"; regex rgx = new regex(baseexpression ); bool returnvalue = rgx.ismatch(testcase);
however, don't know how introduce recursion number can replaced baseexpression;
the examples show integers numbers. want able represent these numeric values floats (or without) decimal point.
anyone have ideas?
in general, regular expression not powerful enough validate parentheses in expression. however, .net supports balancing groups, can used validate expressions follows:
^[^()]*(?>(?>(?'open'\()[^()]*)+(?>(?'-open'\))[^()]*)+)+(?(open)(?!))$
'open'
, '-open'
balancing groups. working of expression explained in article @ link.
even though .net lets in regex, not best approach solving problem, because regex-based solution becomes fragile, "write-once-and-never-touch-again" solution. better off writing simple recursive descent parser task, because solution code in way easy read , lot more maintainable.
Comments
Post a Comment