java - 将高级数学“包括根”字符串转换为由 Java 中的 ScriptEngine 库执行的代码
问题描述
我有一系列高级数学要转换为由 Java 实现的字符串,例如:
String mymath="45+√4+√5+sin(6)+6^3";
我用了
String res= mymath.replace("√",
"Math.sqrt(").replace("sin","Math.sin").replace("^","pow(");
得到结果:
45+Math.sqrt(4+Math.sqrt(5+Math.sin(6)+6pow(3
现在我在转换时关闭括号有问题
解决方案
我想建议一种正则表达式方法。例如,看看这个正则表达式:
√(\d+)|sin\((\d+)\)|(\d+)\^(\d+)
我目前无法访问 IDE,但这在 Notepad++ 中有效,并且想法是相同的。本质上,我提议的是捕获例如 √4,然后将 √ 符号下的数字捕获为一个组。然后,用实际的 sqrt() 函数替换,Math.sqrt\(\1\)
例如,我们只是在括号之间插入组。正弦相同 - 捕获 sin(6) ,其中 6 在一个组中,并替换为Math.sin\(\2\)
. pow() 的想法相同,但这次有两组 - Math.pow\(\3, \4\)
。所以希望你能明白。
问题是您将不得不单独考虑每个数学符号/操作并为其编写单独的正则表达式/替换函数。因此,使用解析器可以为您节省大量时间。
正则表达式演示。
Java Demo(写得很详细以便理解):
public class MathRegex {
public static void main( String args[] ) {
// String to be scanned to find the pattern.
String line = "45+√4+√5+sin(6)+6^3";
String patternSqrt = "√(\\d+)"; // Pattern to find √digit(s)
String patternSine = "sin\\((\\d+)\\)"; // Pattern to find sin(digit(s))
String patternPow = "(\\d+)\\^(\\d+)"; // Pattern to capture digit(s)^digit(s)
// Create a Pattern object
Pattern sqrtPattern = Pattern.compile(patternSqrt);
Pattern sinPattern = Pattern.compile(patternSine);
Pattern powPattern = Pattern.compile(patternPow);
// Now create matcher object for each operation.
Matcher sqrtMatch = sqrtPattern.matcher(line);
String stringSqrt = sqrtMatch.replaceAll("Math.sqrt($1)");
Matcher sinMatch = sinPattern.matcher(stringSqrt); // notice feeding to updated string
String stringSine = sinMatch.replaceAll("Math.sin($1)");
Matcher powMatch = powPattern.matcher(stringSine);
String output = powMatch.replaceAll("pow($1, $2)");
System.out.println(output);
// 45+Math.sqrt(4)+Math.sqrt(5)+Math.sin(6)+pow(6, 3)
}
}
推荐阅读
- python - 在函数中创建和输出数据框
- mongodb - Mongodump:每次备份时备份数据库的大小都会减小
- c# - 如何比较代码的执行时间?
- swiftui-list - 如何在 Mac 上的 SwiftUI 中使用过滤器字段制作列表
- flutter - Flutter 2:颜色问题
- python-3.x - 更改函数参数以产生多个输出时出错
- android - AVD 模拟器没有出现在我的 Android Studio 中
- selenium - Jenkins Chromium 浏览器和 ChromeDriver 版本即使在更新后也不匹配
- c# - 我正在制作井字游戏,但它只是让 X
- spring-boot - 如何使用 POST 端点为 Spring Boot 控制器编写单元测试用例