Terry Li
Terry Li

Reputation: 17268

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

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?

Upvotes: 6

Views: 144

Answers (2)

TomTom
TomTom

Reputation: 1885

In PHP one can do following:

function swap($m) {
    return ($m[0]=='-')?'+':'-';
}
echo preg_replace_callback( '(\+|\-)', 'swap', '1 + 2 - 3 + 4 - 5');

Upvotes: 0

giorashc
giorashc

Reputation: 13713

You can use this trick :

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

Assuming $$$ is not in your equation.

Upvotes: 10

Related Questions