6
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?

Terry Li
  • 16,870
  • 30
  • 89
  • 134
  • 5
    You really shouldn't work on mathematical formulas with regex. Use a tokenizer and work with the tokens. – Daniel Hilgarth Dec 03 '12 at 09:46
  • 1
    Generate a syntax tree from the string, operate on the tree, then render back to string. Much less hassle and far less error prone. – Cubic Dec 03 '12 at 09:48

2 Answers2

10

You can use this trick :

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

Assuming $$$ is not in your equation.

giorashc
  • 13,691
  • 3
  • 35
  • 71
  • 1
    Not very efficient using 3 replaceAll. Besides, you forgot to assign the result of replaceAll to `equation`. – Alex Dec 03 '12 at 09:48
  • 1
    Hey I showed him a trick. I did not say it was efficient, It is just more elegant than iterating – giorashc Dec 03 '12 at 09:50
  • And besides If his equations are not super large this solution will work fast enough to consider trading it off with some more fast but complicated algorithm – giorashc Dec 03 '12 at 09:50
  • I did consider the idea of using temporary variable. You may be aware temporary variable is not necessary when doing value swapping in languages like Ruby. – Terry Li Dec 03 '12 at 10:18
0

In PHP one can do following:

function swap($m) {
    return ($m[0]=='-')?'+':'-';
}
echo preg_replace_callback( '(\+|\-)', 'swap', '1 + 2 - 3 + 4 - 5');
TomTom
  • 1,865
  • 1
  • 13
  • 14
  • For JAVA:http://stackoverflow.com/questions/375420/java-equivalent-to-phps-preg-replace-callback – TomTom Dec 03 '12 at 10:20