2014-03-31 37 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我没有考虑简单地删除字符串的不必要的部分。 –

相关问题