There are numerous scripting languages out there, are you sure reinventing the wheel is the best use of your time? In case you are:
For non-trivial languages, parsing is typically done with a parser generator.
However, for simple cases, writing it by hand isn't too hard. A reasonable approach is recursive decent parsing. In your case, this would look something like:
import java.util.ArrayList;
import java.util.List;
abstract class Expression {
}
class MethodInvocation extends Expression {
final String methodName;
final List<Expression> arguments;
MethodInvocation(String methodName, List<Expression> arguments) {
this.methodName = methodName;
this.arguments = arguments;
}
}
class Literal extends Expression {
final int value;
Literal(int value) {
this.value = value;
}
}
public class Parser {
char[] input;
/** index of next character to consume */
int index;
Parser(String input) {
this.input = input.toCharArray();
index = 0;
}
void consumeExpected(char ch) {
if (input[index] != ch) {
throw new RuntimeException("Syntax Error");
}
index++;
}
String identifier() {
int start = index;
while (index < input.length && Character.isAlphabetic(input[index])) {
index++;
}
return new String(input, start, index - start);
}
Literal numericLiteral() {
int start = index;
if (input[index] == '-') {
index++;
}
while (index < input.length && '0' <= input[index] && input[index] <= '9') {
index++;
}
return new Literal(Integer.parseInt(new String(input, start, index - start)));
}
Expression expression() {
if (Character.isAlphabetic(input[index])) {
String methodName = identifier();
consumeExpected('(');
List<Expression> arguments = new ArrayList<>();
if (input[index] != ')') {
do {
arguments.add(expression());
} while (input[index++] == ',');
index--;
consumeExpected(')');
}
return new MethodInvocation(methodName, arguments);
} else {
return numericLiteral();
}
}
public static void main(String[] args) {
Expression ex = new Parser("R(rndInt(-10,10)),R(rndInt(-10,10))").expression();
System.out.println(ex);
}
}