0

I want to split a mathematical function by the sign of the variables in it like this :

 input-->   x-5y+3z=10

 output--> [x,-5y,+3z,=10]

this code does not work in the way i want :

String function = "x-5y+3z=10";
String split = function.split("=|-|\\+");

the output of the array is :

[x,5y,3z,10]

so what is the correct regex for this ?

azro
  • 53,056
  • 7
  • 34
  • 70
Mohamed Essam
  • 41
  • 1
  • 9

1 Answers1

2

The "problem" using split is that the delimiter used will be removed, because it'll takt the parts that are between this delimiter, you need a pattern that is non-capturing or with a simple lookahead : match something wich is before something else

The pattern (?=[-+=]) would work, it'll take the part that starts with a -+= symbol without removing it :

String function = "x-5y+3z=10";
String[] split = function.split("(?=[-+=])");
System.out.println(Arrays.toString(split)); //[x, -5y, +3z, =10]

Some doc on Lookahead

azro
  • 53,056
  • 7
  • 34
  • 70