Is it possible to switch between + and - using a regular expression in Java?

6*x + 7 = 7*x + 2 - 3*x 

When we move the right side to the left of the equation, we need to flip the operator sign from + to - and vice versa.

Using java regex replaceAll , we can replace all + with -s. As a result, all operator signs become -'s, which makes it impossible to restore all +.

As a workaround, I repeat the line and change + to - when I run into one and vice versa. But I'm still wondering if there is a way to flip between logical pairs of values ​​using regex in Java?

+6
source share
2 answers

You can use this trick:

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

Assuming $$$ is not in your equation.

+10
source

In PHP, you can do the following:

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

All Articles