1

I have a string with a long conditional statement that I need to parse and split up into groups/expressions for visual representation. Here is an example of the source string...

($ROOT.OPT_CHAR1 IN ('val1') AND $ROOT.OPT_CHAR2 IN ('val2')) OR ($ROOT.OPT_CHAR3 IN ('val3') AND $ROOT.OPT_CHAR4 IN ('val4'))

I need to dynamically parse this string and group expressions together appropriately...

Group1: - OR

Group1-A: - AND

$ROOT.OPT_CHAR1 IN ('val1')

$ROOT.OPT_CHAR2 IN ('val2')

Group1-B: - AND

$ROOT.OPT_CHAR3 IN ('val3')

$ROOT.OPT_CHAR4 IN ('val4')

Any help would be appreciated.

vwegert
  • 18,371
  • 3
  • 37
  • 55
  • The evaluation should take into account logical expression Evaluation not only And/Or but also left/right parenthesis . simple splitting or Regex is not suitable for such a problem. You have to build a parser. – M.Hassan Aug 04 '16 at 22:38
  • Agreed. I'm struggling with the logic of creating a parser. – ClintRhodes Aug 05 '16 at 14:35

1 Answers1

0

The evaluation of your expression

($ROOT.OPT_CHAR1 IN ('val1') AND $ROOT.OPT_CHAR2 IN ('val2')) OR ($ROOT.OPT_CHAR3 IN ('val3') AND $ROOT.OPT_CHAR4 IN ('val4'))

should take into account logical expression evaluation, not only AND/OR but also left/right parenthesis for grouping expressions.

Simple splitting or Regex is not suitable for such a problem. You have to build a parser.

To build a parser, you start by defining your grammars: Tokens, rules, ....

You can use ANTLR tool to build/test your grammar and finally generate c# or java Parser and get out of box ready made parser.

Antlr tool takes the grammar file as an input and generates two classes: lexer and parser

First, you create tokens for each operator and parenthesis:

LPAREN : '(' ;
RPAREN : ')' ;
AND : 'AND';
OR : 'OR';
IN : 'IN';

Define your variable like ROOT.OPT_CHAR1: Names are composed of letters and digits:

 NAME : ('a'..'z' | '0'..'9')*;

Define white spaces: WS : ( ' ' | '\t' | '\r' | '\n' );

Finally create parser rules.

For Details of Grammer structure, read: Grammar Structure

Reading simple tutorial for Antllr help you build your parser.

M.Hassan
  • 10,282
  • 5
  • 65
  • 84
  • I have no idea what that ANTLR tool is. – ClintRhodes Aug 08 '16 at 19:59
  • ANTLR tool is a powerfull parser generator, read reference in my answer to build your grammar and generate c# parser that can process text files based on that grammer. read SO http://stackoverflow.com/questions/1931307/antlr-is-there-a-simple-example. – M.Hassan Aug 08 '16 at 21:29