Java Variable Substitution

This is normally solved with just a String#replaceAll, but since you have a custom, dynamic replacement string, you can to use a Matcher to efficiently and concisely do the string replacement.

public static String parse(String command, String... args) {
    StringBuffer sb = new StringBuffer();
    Matcher m = Pattern.compile("\\$(\\d+)").matcher(command);
    while (m.find()) {
        int num = Integer.parseInt(m.group(1));
        m.appendReplacement(sb, args[num - 1]);
    }
    m.appendTail(sb);
    return sb.toString();
}

Ideone Demo

Leave a Comment