Search code examples
javaandroidreplacereplaceall

android - java.lang.ArrayIndexOutOfBoundsException when using replaceAll on a specific string containing special characters


PROBLEM

I'm using Abatis as ORM. When I try to insert a json containing a specific string it crashes.

I have extracted the code from Abatis that generates the error:

CODE

            Map<String, Object> bindParams = new HashMap<String, Object>();

            bindParams.put("id", "194fa0f2-9706-493f-97ab-4eb300a8e4ed");
            bindParams.put("field", "{\"Messages\":\"ERRORE durante l'invocazione del servizio. 01 - Executor [java.util.concurrent.ThreadPoolExecutor@18a96588] did not accept task: org.springframework.aop.interceptor.AsyncExecutionInterceptor$1@14a7c67b\",\"Errors\":1}");

            String sql = "UPDATE <TABLE> SET NoteAgente = #field# WHERE Id = #id#";

            if (bindParams != null) {
                Iterator<String> mapIterator = bindParams.keySet().iterator();
                while (mapIterator.hasNext()) {
                    String key = mapIterator.next();
                    Object value = bindParams.get(key);

                    if(value instanceof String && value != null)
                        value = value.toString().replace("'", "''");

                    sql = sql.replaceAll("#" + key + "#", value == null ? "null"
                            : "'" + value.toString() + "'");
                }
            }

The problem is in the replaceAll method with the string $1@14a7c67b. You can also debug it writing

String s = "onetwothree";               
s = s.replaceAll("one", "$1@14a7c67b");

and it will also crashes.


Solution

  • replaceAll takes a regular expression argument, and $1 is a special way of telling the java regex engine to use group-one as the replacement.

    You need to use replace which matches/replaces the string literally:

    String s = "onetwothree";
    s = s.replace("one", "$1@14a7c67b");
    

    You could also escape the $ character if you still need to use replaceAll:

    s = s.replaceAll("one", "\\$1@14a7c67b");