android - 在包含特殊字符的特定字符串上使用replaceAll时出现java.lang.ArrayIndexOutOfBoundsException

Lin*_* 88 1 java android replace replaceall

问题

我使用 Abatis 作为 ORM。当我尝试插入包含特定字符串的 json 时,它崩溃了。

我从 Abatis 中提取了生成错误的代码:

代码

            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() + "'");
                }
            }
Run Code Online (Sandbox Code Playgroud)

问题出在带有字符串$1@14a7c67b的ReplaceAll方法中。您还可以调试它写作

String s = "onetwothree";               
s = s.replaceAll("one", "$1@14a7c67b");
Run Code Online (Sandbox Code Playgroud)

它也会崩溃。

epo*_*och 6

replaceAll采用正则表达式参数,$1是一种告诉 java 正则表达式引擎使用 group-one 作为替换的特殊方式。

您需要使用replacewhich 字面匹配/替换字符串:

String s = "onetwothree";
s = s.replace("one", "$1@14a7c67b");
Run Code Online (Sandbox Code Playgroud)

$如果您仍然需要使用,您也可以转义该字符replaceAll

s = s.replaceAll("one", "\\$1@14a7c67b");
Run Code Online (Sandbox Code Playgroud)