I need two regular expressions to identify if .. then .. else .. endif section and their parts.
From an expression which could be like below:
Example 1:
5 + 10 * (if (4 + 4.5) > 0 then 20 else 45 endif) + 2
Example 2:
if (20 == 10) then 10 endif
Example 3:
if (20/10 != 2) then (2 * 10) else (3 * 4) endif
Expected Result:
-
A regular expression which could give me the
if..endifpart in an expression
For ex. from Example 1 I should receiveif (4 + 4.5) > 0 then 20 else 45 endifseparately -
A regular expression which could give me the
if..endifparts.
For ex. from Example 1 I should receive:
Left-Comparator: (4 + 4.5)
Operator: >
Right-Comparator: 0
ThenPart: 20
ElsePart: 45 (could be null or string.Empty)
Points to Note:
elseis optional.if..endifcould be the only expression or it could be part of a expression.then&elsecan have an expression or a static value.- The conditional operators that could be used in if condition are
>, <, ==, !=, >=, <= - Regular Expression should work in C# application.
Regular expressions are not well suited to this kind of job because you can do nested
if/then/elseand because of the possible variations (lack ofelse, for example); the Regex would be massive and it would take A LOT of work to balance the greediness/laziness of each capture. It would be much easier to scan each character and generate an expression tree that you could then interpret. Regex are more suited to text parsing where the format is known or where there is little variation.EDIT
After thinking about it, it wasn’t that hard:
if( *.*? *)then( *.*? *)(?:else( *.*? *))?endifEach capturing group contains the components:
elseis present)I make no guarantees on accuracy, because it doesn’t work with nested
ifexpressions, but for your needs it should be sufficient.