【问题标题】:android - java.lang.ArrayIndexOutOfBoundsException when using replaceAll on a specific string containing special charactersandroid - 在包含特殊字符的特定字符串上使用 replaceAll 时出现 java.lang.ArrayIndexOutOfBoundsException
【发布时间】:2015-07-23 10:42:12
【问题描述】:

问题

我使用 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() + "'");
                }
            }

问题在于字符串 $1@14a7c67breplaceAll 方法。你也可以调试它写

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

它也会崩溃。

【问题讨论】:

    标签: java android replace replaceall


    【解决方案1】:

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

    您需要使用 replace 来匹配/替换字符串:

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

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

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

    【讨论】:

    • 完美答案!它就像一个魅力!不能只将此标记为答案,我会尽快完成。
    • 另见stackoverflow.com/a/50047372/245966;另请注意,与 JavaScript 不同,在 Java 中 replace 会替换所有出现的位置,而不仅仅是第一个!
    猜你喜欢
    • 1970-01-01
    • 2020-12-25
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    相关资源
    最近更新 更多