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?

2
  • 5
    You really shouldn't work on mathematical formulas with regex. Use a tokenizer and work with the tokens. Commented Dec 3, 2012 at 9: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. Commented Dec 3, 2012 at 9:48

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Not very efficient using 3 replaceAll. Besides, you forgot to assign the result of replaceAll to equation.
Hey I showed him a trick. I did not say it was efficient, It is just more elegant than iterating
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
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.
0

In PHP one can do following:

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

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.