zoukankan      html  css  js  c++  java
  • replaceAll的一个bug

    String replaceAll(regex, replacement)函数 , 由于第一个参数支持正则表达式,replacement中出现“$”,会按照$1$2的分组
    模式进行匹配,当编译器发现“$”后跟的不是整数的时候,就会抛出“非法的组引用”的异常。
    所以我们在使用replaceAll(regex, replacement)函数的时候要特别小心。

    问题1: 如果replacement中带有字符 $ ,则会报错

    java.lang.IllegalArgumentException: Illegal group reference

    问题2: 如果replacement中带有字符 ,则会报错

    java.lang.IllegalArgumentException: character to be escaped is missing

    解决办法:
    在执行replaceAll时,对replacement字段的值进行关键字替换

    replacement = Matcher.quoteReplacement(replacement);

    示例代码1:【主要】

                String replacement = entry.getValue();
                replacement = Matcher.quoteReplacement(replacement);
                template = template.replaceAll("\$\{".concat(entry.getKey().trim()).concat("\}"), replacement);


    示例代码2:

        private String replacePlaceholder(String sql, Object propertyValue) {
            String result;
            if (propertyValue != null) {
                if (propertyValue instanceof String) {
                    result = "'" + propertyValue + "'";
                } else if (propertyValue instanceof Date) {
                    result = "'" + DATE_FORMAT.format(propertyValue) + "'";
                } else {
                    result = propertyValue.toString();
                }
            } else {
                result = "null";
            }
            return sql.replaceFirst("\?", Matcher.quoteReplacement(result));
        }

    https://github.com/abel533/Mapper/issues/30


    github代码

    参考:
    https://stackoverflow.com/questions/11913709/why-does-replaceall-fail-with-illegal-group-reference
    http://www.javacui.com/java/45.html
    http://jerval.iteye.com/blog/2164227


  • 相关阅读:
    centos下安装mycat
    centos下安装MySQL5.7
    centos下yum安装wget失败
    开心消消乐刷金币
    myBatis获取批量插入数据的主键id
    nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied)
    Mac下安装JDK 6
    VI下删除所有内容
    Mac下lombok无法安装到eclipse mars
    WEB-INF目录下的文件访问权限
  • 原文地址:https://www.cnblogs.com/softidea/p/9931495.html
Copyright © 2011-2022 走看看