Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking apart a math equation string

Tags:

java

regex

    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

how can I do this?

like image 934
Dallas Avatar asked Feb 15 '26 02:02

Dallas


1 Answers

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));
    }
}
like image 198
Boro Avatar answered Feb 16 '26 15:02

Boro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!