我希望有一个正则表达式,它可以检测最后的数学表达式,以便改变表达式的符号,例如:
5 --> -5
-5 --> 5
5+2*cos(10) --> 5-2*cos(10)
5-cos(10+2) --> 5+cos(10+2)我仍然无法创建任何能与最后表达式匹配的正则表达式。我创建了这个regex (\+[(cos|sin|tan)])+(.*[0-9]*.),但是它只在有sin/cos或tan时选择最后一个表达式。
发布于 2019-01-13 19:48:37
很抱歉迟到(难以置信地),但我的解决办法是:
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);我正在使用BlueJ作为IDE,顺便说一句。
下面是一个现场演示:https://regex101.com/r/3EM9Ix/1
解释
(\\+|-)选择所需的运算符,“+”或“-”(?=(?:[a-zA-Z]*\\(.*?\\))|[0-9^*/]+$)是检查运算符后面是否有字母的函数或只是更多数字的正则表达式。
https://stackoverflow.com/questions/53322053
复制相似问题