1
String Equation = input.nextLine();
String[] number = Equation.split("\d+");

I want to split all digits come into string and dump into number. How'd do it?

like Equation is : 2x^4 - 45y^4

it should be dumped in number on index as : {2, 4 , 45, 4};

3
  • 2
    There's no escape sequence \d in java. Your code won't ocmpile. Commented Oct 9, 2013 at 18:45
  • @RaptorDotCpp it will not compile. Commented Oct 9, 2013 at 18:47
  • So how it can be done. how'd split them? Commented Oct 9, 2013 at 18:47

2 Answers 2

8

You can split on one or more non-digit characters - \\D+:

String[] number = equation.split("\\D+");

While working with Java regex, you need to double escape the \d, \D, so on. And please follow Java naming convention. Your variable should be named equation, not Equation.

Sign up to request clarification or add additional context in comments.

Comments

3

What I'd do is String.replaceAll all non-digits with whitespace. Then String.split by whitespace.

package com.sandbox;


import java.util.Arrays;

public class Sandbox {
    public static void main(String[] args) {
        String input = "2x^4 - 45y^4";
        input = input.replaceAll("\\D", " ");
        String[] parts = input.split("\\W+");

        System.out.println(Arrays.toString(parts));
    }
}

This will print "[2, 4, 45, 4]"


Now that I understand @RohitJain's answer, it seems I'm including an unnecessary step. I guess I'll leave this here anyway since it does work, but I recommend his solution. His solution splits on all non digits. Since split excludes the delimiter, this also removes the non-digits.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.