I would like to suggest a regex approach. For example, take a look at this regex:
√(\d+)|sin\((\d+)\)|(\d+)\^(\d+)
I don't have an access to an IDE at the moment, but this works in Notepad++ and the idea is the same. Essentially what I am proposing is to capture e.g. √4, and then capture the digit(s) under the √ sign as a group. Then, replace with the actual sqrt() function, so Math.sqrt\(\1\)
, for example, where we are simply inserting the group between the parenthesis. Same for sine - capture sin(6) with 6 being in a group, and replace with Math.sin\(\2\)
. Same idea for pow(), but this time have two groups - Math.pow\(\3, \4\)
. So hopefully you get the idea.
The problem is that you will have to separately think about every math symbol/operation and write out a separate regex/replacement function for it. So using a parser would save you a lot of time.
Regex demo to play around.
Java Demo (written out verbose for understanding):
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)
}
}