static String replaceParameters(String format,
                                    String[] params) throws BadFormatString {
        Matcher match = PARAMETER_PATTERN.matcher(format);
        int start = 0;
        StringBuilder result = new StringBuilder();
        while (start < format.length() && match.find(start)) {
            result.append(match.group(1));
            String paramNum = match.group(3);
            if (paramNum != null) {
                try {
                    int num = Integer.parseInt(paramNum);
                    if (num < 0 || num >= params.length) {
                        throw new BadFormatString("index " + num + " from " + format +
                                " is outside of the valid range 0 to " +
                                (params.length - 1));
                    }
                    result.append(params[num]);
                } catch (NumberFormatException nfe) {
                    throw new BadFormatString("bad format in username mapping in " +
                            paramNum, nfe);
                }

            }
            start = match.end();
        }
        return result.toString();
    }
@Test
    public void testReplaceParameters() throws BadFormatString {
        // positive test cases
        assertEquals(KerberosRule.replaceParameters("", new String[0]), "");
        assertEquals(KerberosRule.replaceParameters("hello", new String[0]), "hello");
        assertEquals(KerberosRule.replaceParameters("", new String[]{"too", "many", "parameters", "are", "ok"}), "");
        assertEquals(KerberosRule.replaceParameters("hello", new String[]{"too", "many", "parameters", "are", "ok"}), "hello");
        assertEquals(KerberosRule.replaceParameters("hello $0", new String[]{"too", "many", "parameters", "are", "ok"}), "hello too");
        assertEquals(KerberosRule.replaceParameters("hello $0", new String[]{"no recursion $1"}), "hello no recursion $1");

        // negative test cases
        assertThrows(
            BadFormatString.class,
            () -> KerberosRule.replaceParameters("$0", new String[]{}),
            "An out-of-bounds parameter number should trigger an exception!");

        assertThrows(
            BadFormatString.class,
            () -> KerberosRule.replaceParameters("hello $a", new String[]{"does not matter"}),
            "A malformed parameter name should trigger an exception!");
    }