AndroLife :
I want to have a regex that can detect last math expression in order to change sign of that expression for example :
5 --> -5
-5 --> 5
5+2*cos(10) --> 5-2*cos(10)
5-cos(10+2) --> 5+cos(10+2)
I still couldn't create any regex that can match last expression. I created this regex (\+[(cos|sin|tan)])+(.*[0-9]*.)
but it only select the last expression if there is a sin/cos or tan.
Robo Mop :
Sorry for being (incredibly) late to the party, but here's my solution:
String str = "5*10/2+cos(54/90)", regex = "(\\+|-)(?=(?:[a-zA-Z]*\\(.*?\\))|[0-9^*/]+$)";
Pattern pat = Pattern.compile(regex);
Matcher m = pat.matcher(str);
String r = "";
if(m.find())
{
r = m.group(1).equals("+")?"-":"+";
}
str = str.replaceAll(regex, r);
System.out.println(str);
I'm using BlueJ as an IDE, btw.
Here's a live demo: https://regex101.com/r/3EM9Ix/1
EXPLANATION
(\\+|-)
selects the desired operator, '+' or '-' (?=(?:[a-zA-Z]*\\(.*?\\))|[0-9^*/]+$)
is the regex that checks if the operator is followed by either a function which has letters in it or just some more digits