2014-03-31 41 views
2

我想輸入「sin(35)」到文本字段中,但要計算它,我必須用空格分隔每個運算符和數字,因爲我使用了.split(「 ),如何將分隔符設置爲數字或運算符後的空字符串,以便它可以不接受空格?如何在一個字後標記空字符串

pseudocode: infix.split("" after sin | "" after [()+-*^]) 
+0

我不明白你的意思,你可以澄清一個例子嗎? – Keppil

+1

我在最後看不到空格。你確定你不能用'.trim()'忽略它嗎? –

+0

你的意思是你想用'「」分隔而不是空格?如果是的話,那是不可能的。你需要使用substring,indexOf,...方法 –

回答

2

如果你只是想用拆分獲得公式參數,你可以使用PatternMatcher類代替,就像這樣:

String function = ""; 
int parameter = 0; 
Pattern pattern = Pattern.compile("(sin)\\((\\d+)\\)"); // Compile the regex pattern. 
Matcher matcher = pattern.matcher("sin(35)");   // Instantiate a pattern Matcher to search the string. 
while (matcher.find()) {        // For every match... 
    function = matcher.group(1);      // Get group `$1`. 
    String s = matcher.group(2);      // Get group `$2`. 
    parameter = Integer.parseInt(s);     // Parse to int, throws `NumberFormatException` if $2 is not a number. 
} 
System.out.println(function);       // Prints "sin". 
System.out.println(parameter);       // Prints 35. 

正則表達式:

(sin)\((\d+)\) 

Regular expression visualization

+1

你是如何創建這個圖像的? :) – AKS

+2

@AKS [Debuggex.com](http://www.debuggex.com) –

1

您只需要一行提取每個p藝術:

String function = input.replaceAll("\\(.*", ""); 
String parameter = input.replaceAll(".*\\(|\\).*", ""); 
+0

+1我沒有考慮簡單地刪除字符串的不必要的部分。 –

相關問題