簡體   English   中英

將字符串表達式拆分為標記

[英]Splitting string expression into tokens

我的意見就像

String str = "-1.33E+4-helloeeee+4+(5*2(10/2)5*10)/2";

我希望輸出為:

1.33E+4
helloeeee
4
5
2
10
2
5
10
2

但是我得到了輸出

1.33, 4, helloeeee, 4, 5, 2, 10, 2, 5, 10, 2

在分割“1.33e + 4”后我想完全指數值

這是我的代碼:

    String str = "-1.33E+4-helloeeee+4+(5*2(10/2)5*10)/2";
    List<String> tokensOfExpression = new ArrayList<String>();
    String[] tokens=str.split("[(?!E)+*\\-/()]+");
    for(String token:tokens)
    {   
         System.out.println(token);
         tokensOfExpression.add(token);
    }
    if(tokensOfExpression.get(0).equals(""))
    {
         tokensOfExpression.remove(0);
    }

你不能用一個正則表達式來做到這一點,因為FP常量在科學記數法中引入了歧義,並且在任何情況下你都需要知道哪個令牌不需要重新掃描它們。 你也錯誤地說明了你的要求,因為你當然也需要輸出中的二元運算符。 您需要同時編寫掃描程序和解析程序。 看看'遞歸下降表達式解析器'和'Dijkstra shunting-yard算法'。重新設置摘要是多余的。

我首先用一個不含糊的符號替換E +,例如

str.ReplaceAll("E+","SCINOT");

然后,您可以使用StringTokenizer進行解析,在需要評估科學計數法表示的數字時替換SCINOT符號。

嘗試這個

String[] tokens=str.split("(?<!E)+[*\\-/()+]");

使用Matcher更容易實現結果

    String str = "-1.33E+4-helloeeee+4+(5*2(10/2)5*10)/2";
    Matcher m = Pattern.compile("\\d+\\.\\d*E[+-]?\\d+|\\w+").matcher(str);
    while(m.find()) {
        System.out.println(m.group());
    }

版畫

1.33E+4
helloeeee
4
5
2
10
2
5
10
2

請注意,它需要對不同的浮點表達式進行一些測試,但它很容易調整

暫無
暫無

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

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