簡體   English   中英

在 java 中使用算術運算符和函數拆分字符串

[英]Splitting the String with arithmetic operators and functions in java

我需要一些關於如何使用 java 中的算術運算符和函數拆分字符串的指導,例如 String 是:

"string1"+"String2" >= 10 * function1() / function2()

運營商可能是:

+ - * / ** / % / ( ) = != > < <= >=

拆分后,我需要 output ,例如:

array[0]=string1
array[1]=string2
array[2]=10

我只需要雙引號和內容或數字內的東西,而不是函數(function1())或運算符。

我需要正則表達式來解決這個問題

您可以從字符串中刪除所有運算符,然后將除字符串之外的所有內容都與最后的()匹配。

我建議創建一個解析器,例如使用 JavaCC 或parboiled https://github.com/sirthias/parboiled/wiki/ (還沒有嘗試過)

如果您需要一個正則表達式來提取雙引號和數字中的內容,那么您可以使用此 java 代碼:

public static void main(String[] args) {
    Pattern p = Pattern.compile("\"(\\w+)\"|\\b\\d+\\b");
    Matcher m = p.matcher(
        "\"string1\"+\"String2\" >= 10 * function1() / function2()");
    List<String> parts = new ArrayList<String>();
    while (m.find()) {
        if (m.group(1) != null)
            parts.add(m.group(1));
        else
            parts.add(m.group(0));
    }
    System.out.println(Arrays.toString(parts.toArray(new String[] {})));        
}

輸出:

[string1, String2, 10]

注意:我不確定正則表達式是這種情況下的最佳工具。 正如其他人建議的那樣,您可能想要調查解析器的使用。

暫無
暫無

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

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