0

i have an String and i need to split this String to array My String is for example "-2x+3"

i split it with this code

public static String[] splitAnswer(String answerInput){
        answerInput = answerInput.trim();
        String[] token = answerInput.split("[\\+\\-\\*\\\\\\/]");
        return token;
    }

but i need the minus sign with 2x i.e. (-2x) and my array output will be {"-2x","3"} the important thing i need the minus with the number after

2
  • What is the expected output from the input "-2x+3"? Commented Apr 16, 2015 at 17:35
  • my purpose to check the answer of student if it's right or not for example if the answer is -2x+3 and the student answer +3-2x the answer must be correct that what i search to Commented Apr 16, 2015 at 17:39

1 Answer 1

2

You can use following regex:

String[] token = answerInput.split("[+*/]|(?=-)")

So, this splits on all the operators, except -. For - operator, it splits on empty string before the - operator. BTW, you don't need to escape anything inside the character class.

For -2x + 3, the split positions are:

|-2x+3   ( `|` is empty space)
^   ^
Sign up to request clarification or add additional context in comments.

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.