博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
replaceAll的一个bug
阅读量:6895 次
发布时间:2019-06-27

本文共 1543 字,大约阅读时间需要 5 分钟。

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

 

参考:

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

 

转载于:https://www.cnblogs.com/softidea/p/9931495.html

你可能感兴趣的文章
推荐几款API文档集合工具
查看>>
代码照亮宝贝回家路
查看>>
OTL之Oracle开发总结《转》
查看>>
php取整函数ceil,floor,round,intval函数的区别
查看>>
安卓应用安全指南 4.2.2 创建/使用广播接收器 规则书
查看>>
Stratus Technologies与海得控制升级长期战略合作,助力中国工业自动化与工业物联网解决方案...
查看>>
新建的SQL Server账号无法使用跟踪功能
查看>>
远程线程注入引出的问题
查看>>
「镁客·请讲」NXROBO林天麟:我们分三步走,首先要做的就是打通机器人行业的产业链...
查看>>
这款创意相机,能让盲人更真实的感触身边世界
查看>>
hdu 1285 确定比赛名次(很典型的拓扑排序)
查看>>
学习iOS【3】数组、词典和集合
查看>>
8Python全栈之路系列之Django Cookie 与Sessi
查看>>
nginx反向代理配置
查看>>
DecimalFormat用法
查看>>
一致性哈希算法及其在分布式系统中的应用
查看>>
流程DEMO-出差申请单
查看>>
阿里巴巴与清华大学成立联合实验室,十问十答看人机交互未来时间表
查看>>
mybatis-添加操作
查看>>
黑莓与AR眼镜生产商Vuzix联手,为其提供数据安全服务
查看>>