Is it possible to switch between + and - using regex in Java?

java, regex, replace

Solution

You can use this trick :

String equation = "<Your equation>"
equation = equation.replaceAll("+","$$$");
equation = equation.replaceAll("-","+");
equation = equation.replaceAll("$$$","-");

Assuming $$$ is not in your equation.

Problem

``` 6*x + 7 = 7*x + 2 - 3*x ``` When we move the right hand side to the left of the equation, we need to flip the operator sign from + to - and vice versa. Using java regex `replaceAll`, we're able to replace all +'s with -'s. As a result, all the operator signs become -'s, making it impossible for us to recover all the +'s. As a workaround, I'm iterating through the string and changing + to - when encountering one and vice versa. But I still wonder if there's a way to flip between boolean value pairs using regex in Java?

Original source

Related problems