Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 667
Terry Li Avatar asked Dec 03 '12 09:12

Terry Li


People also ask

Can I use regex in switch case?

You can't do it in a switch unless you're doing full string matching; that's doing substring matching.

Can we use regex in replace Java?

regex package for searching and replacing matching characters or substring. Since String is immutable in Java it cannot be changed, hence this method returns a new modified String. If you want to use that String you must store it back on the relevant variable.

How do you find and replace in a regular expression in Java?

They can be used to search, edit, or manipulate text and data. The replaceFirst() and replaceAll() methods replace the text that matches a given regular expression. As their names indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurrences.

What does \\ mean in Java regex?

The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.


1 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.

like image 73
giorashc Avatar answered Sep 21 '22 00:09

giorashc