首页 > 解决方案 > 将高级数学“包括根”字符串转换为由 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

现在我在转换时关闭括号有问题

标签: javaandroidregexmath

解决方案


我想建议一种正则表达式方法。例如,看看这个正则表达式:

√(\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)
    }
}

推荐阅读