Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract from string in Java

Tags:

java

regex

split

I have a string;

String value = "(5+5) + ((5+8 + (85*4))+524)";

How can I split/extract logical values from this string inside parenthesis as;

(85*4) as one
(5+8 + one) as two
(two+524) as three
((5+5) + three) as four
...

Any idea? all is welcome

like image 775
Adnan Avatar asked Jun 04 '10 08:06

Adnan


People also ask

How do you extract a string from a string?

You call the Substring(Int32) method to extract a substring from a string that begins at a specified character position and ends at the end of the string. The starting character position is zero-based; in other words, the first character in the string is at index 0, not index 1.


1 Answers

This cannot be done using some cleaver regular expression (regular expressions can not "count parenthesis"). Your best option is to use some parser generator and parse the string into an abstract syntax tree (AST for short).

Have a look at JFlex/JavaCUP for instance.


As it turns out, the CUP manual actually has an example covering your situation:

// CUP specification for a simple expression evaluator (w/ actions)

import java_cup.runtime.*;

/* Preliminaries to set up and use the scanner.  */
init with {: scanner.init();              :};
scan with {: return scanner.next_token(); :};

/* Terminals (tokens returned by the scanner). */
terminal           SEMI, PLUS, MINUS, TIMES, DIVIDE, MOD;
terminal           UMINUS, LPAREN, RPAREN;
terminal Integer   NUMBER;

/* Non-terminals */
non terminal            expr_list, expr_part;
non terminal Integer    expr;

/* Precedences */
precedence left PLUS, MINUS;
precedence left TIMES, DIVIDE, MOD;
precedence left UMINUS;

/* The grammar */
expr_list ::= expr_list expr_part 
          | 
              expr_part;

expr_part ::= expr:e 
          {: System.out.println("= " + e); :} 
              SEMI              
          ;

expr      ::= expr:e1 PLUS expr:e2    
          {: RESULT = new Integer(e1.intValue() + e2.intValue()); :} 
          | 
              expr:e1 MINUS expr:e2    
              {: RESULT = new Integer(e1.intValue() - e2.intValue()); :} 
          | 
              expr:e1 TIMES expr:e2 
          {: RESULT = new Integer(e1.intValue() * e2.intValue()); :} 
          | 
              expr:e1 DIVIDE expr:e2 
          {: RESULT = new Integer(e1.intValue() / e2.intValue()); :} 
          | 
              expr:e1 MOD expr:e2 
          {: RESULT = new Integer(e1.intValue() % e2.intValue()); :} 
          | 
              NUMBER:n                 
          {: RESULT = n; :} 
          | 
              MINUS expr:e             
          {: RESULT = new Integer(0 - e.intValue()); :} 
          %prec UMINUS
          | 
              LPAREN expr:e RPAREN     
          {: RESULT = e; :} 
          ;
like image 135
aioobe Avatar answered Sep 18 '22 02:09

aioobe