加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

从Java中的字符串中提取

发布时间:2020-12-14 05:41:11 所属栏目: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... 任何的想法?一切都很受欢迎 解决方法 这不能使用一些切割器
我有一个字符串;
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
...

任何的想法?一切都很受欢迎

解决方法

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

例如,请查看JFlex/JavaCUP.

事实证明,CUP manual实际上有一个例子涵盖你的情况:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读