Break the line of a mathematical equation

    Pattern pattern = Pattern.compile("([^\\d.]|[\\d.]++)");
    String[] equation =  pattern.split("5+3--323");
    System.out.println(equation.length);

I'm trying to split numbers (there may be groups) and nonnumber, in this example I was hoping for an array of size 6: 5, +, 3, -, -, 323

How can i do this?

+3
source share
3 answers

Try using a match, as in the 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));
    }
}
+7
source

How about using

new java.util.Scanner(new java.io.StringReader("5+3--323"));

instead

http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html

+2
source

If your numbers are separated by commas, first wrap the String;

tok = new StringTokenizer(string, ",");

then try to create a number from each token. If this is not a number, then this is a symbol:

while (tok.hasMoreTokens()){
    String tok = tok.nextTok();
    try {
          new Integer(tok);
    }catch (NumberFormatException e){

    }
}

If tok is not a number, a NumberFormatException is thrown.

+2
source