[英]Breaking apart a math equation string
Pattern pattern = Pattern.compile("([^\\d.]|[\\d.]++)");
String[] equation = pattern.split("5+3--323");
System.out.println(equation.length);
I'm trying to break apart numbers (could be groups) and nonnumbers, in this example i was hoping for a size 6 array: 5, +, 3, -, -, 323我试图分解数字(可能是组)和非数字,在这个例子中我希望一个大小为 6 的数组:5、+、3、-、-、323
how can I do this?我怎样才能做到这一点?
Try using matcher, as in example below.尝试使用匹配器,如下例所示。 It returns exactly what you are after.
它会准确地返回您所追求的。
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MathSplitTest
{
public static void main(String[] args)
{
Pattern pattern = Pattern.compile("[0-9]+|[-+]");
String string = "5+3--323";
Matcher matcher = pattern.matcher(string);
while(matcher.find())
System.out.println("g0="+matcher.group(0));
}
}
What about using a使用一个怎么样
new java.util.Scanner(new java.io.StringReader("5+3--323"));
instead?反而?
http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
If your numbers are comma separated then first tokenize the String;如果您的数字以逗号分隔,则首先标记字符串;
tok = new StringTokenizer(string, ",");
then try to create a number from each token.然后尝试从每个令牌创建一个数字。 If it is not a number then it's a symbol:
如果它不是数字,那么它是一个符号:
while (tok.hasMoreTokens()){
String tok = tok.nextTok();
try {
new Integer(tok);
}catch (NumberFormatException e){
}
}
If tok is not a number then a NumberFormatException is thrown.如果 tok 不是数字,则抛出 NumberFormatException。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.