views:

63

answers:

2

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:

  1. A regular expression which could give me the if..endif part in an expression For ex. from Example 1 I should receive if (4 + 4.5) > 0 then 20 else 45 endif separately

  2. A regular expression which could give me the if..endif parts. 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:

  1. else is optional.
  2. if..endif could be the only expression or it could be part of a expression.
  3. then & else can have an expression or a static value.
  4. The conditional operators that could be used in if condition are >, <, ==, !=, >=, <=
  5. Regular Expression should work in C# application.
+5  A: 

Regular expressions are not well suited to this kind of job because you can do nested if/then/else and because of the possible variations (lack of else, 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( *.*? *))?endif

Each capturing group contains the components:

  1. The condition
  2. Value for true
  3. Value for false (only when else is present)

I make no guarantees on accuracy, because it doesn't work with nested if expressions, but for your needs it should be sufficient.

SimpleCoder
@SimpleCoder: I understand that but could anyone provide me regex on how to do that. I need to know the regex for that for a client. I just need the regex for that. Thanks
I added an example Regex
SimpleCoder
+1 thanks your regex works :)
You are welcome. If you have found my answer useful please accept it as the correct answer.
SimpleCoder
@SimpleCoder: Sure sorry forgot that thanks again :)
+1  A: 

Why do you think you need a regular expression? In a case like this, I would write a small parser, for example using ANTLR. Maintaining a parser grammar for complex expressions is usually less painful than regular expressions, with the added benefit of providing better error messages with context information and the like.

Jim Brissom