簡體   English   中英

從Java中的字符串中提取

[英]Extract from string in Java

我有一個字符串;

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)。

例如,看看JFlex / JavaCUP


事實證明, CUP手冊實際上有一個例子涵蓋你的情況:

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

您可以為表達式模型生成解析器,例如使用JavaCC ,然后將表達式字符串解析為表達式樹。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM