Java中的字符串提取

Java中的字符串提取,java,regex,split,Java,Regex,Split,我有一根绳子 String value = "(5+5) + ((5+8 + (85*4))+524)"; 如何从括号内的字符串中拆分/提取逻辑值,如下所示: (85*4) as one (5+8 + one) as two (two+524) as three ((5+5) + three) as four ... 有什么想法吗?一切都是受欢迎的这不能使用某些解理器正则表达式来完成(正则表达式不能“计算括号”)。您最好的选择是使用一些解析器生成器,并将字符串解析为(简称AST) 例如看一看

我有一根绳子

String value = "(5+5) + ((5+8 + (85*4))+524)";
如何从括号内的字符串中拆分/提取逻辑值,如下所示:

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

有什么想法吗?一切都是受欢迎的

这不能使用某些解理器正则表达式来完成(正则表达式不能“计算括号”)。您最好的选择是使用一些解析器生成器,并将字符串解析为(简称AST)

例如看一看


事实证明,实际上有一个例子涵盖了您的情况:

// 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; :} 
          ;

您可以为表达式模型生成一个解析器,例如使用,然后将表达式字符串解析到表达式树中。

谢谢,我正在研究它。您不会后悔的。解析器生成器在轻松完成复杂的解析时非常有用。