문자열이 있습니다.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
...
아이디어가 있으십니까? 모두 환영합니다
문자열이 있습니다.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
...
아이디어가 있으십니까? 모두 환영합니다
일부 식 물자 정규식 (정규식은 "괄호"수 없습니다)을 사용하여 수행 할 수 없습니다. 가장 좋은 방법은 일부 파서 생성기를 사용하고 문자열을 abstract syntax tree (간단히 대서양 표준시)으로 구문 분석하는 것입니다.
예를 들어 JFlex/JavaCUP을 살펴보십시오. 당신은 JavaCC으로 예를 들어, 표현 모델의 파서를 생성 한 다음에 표현 문자열을 구문 분석 할 수
// 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; :}
;
감사합니다. – Adnan
후회하지 않을 것입니다. 파서 생성기는 복잡한 구문 분석을 쉽게 수행 할 때 매우 유용합니다. – aioobe