java - Java RegEx doesn't replaceAll
问题描述
I was trying to replace concatenation symbol '+' with '||' in given multi-line script, however it seems that java regex just replaces 1 occurrence, instead of all.
String ss="A+B+C+D";
Matcher mm=Pattern.compile("(?imc)(.+)\\s*\\+\\s*(.+)").matcher(ss);
while(mm.find())
{
System.out.println(mm.group(1));
System.out.println(mm.group(2));
ss=mm.replaceAll("$1 \\|\\| $2");
}
System.out.println(ss); // Output: A+B+C||D, Expected: A||B||C||D
解决方案
You could just use:
ss = ss.replaceAll("\\+", "||")
as @ernest_k has pointed out. If you really want to continue using a matcher with iteration, then use Matcher#appendReplacement
with a StringBuffer
:
String ss = "A+B+C+D";
Matcher mm = Pattern.compile("\\+").matcher(ss);
StringBuffer sb = new StringBuffer();
while (mm.find()) {
mm.appendReplacement(sb, "||");
}
mm.appendTail(sb);
System.out.println(sb);
推荐阅读
- angular-ng-if - 使用 ngif 进行表单验证的反应式表单中的 Angular 10 双向数据绑定
- vue.js - 如何:Vue3 组合 API 插件
- php - Laravel:如何将数组从查询结果中分离成变量?
- java - 指定 URI 没有路径映射时无法捕获 404 异常
- java - 在 Spring Boot 应用程序中序列化 API 请求参数的问题
- angular - 如何去除 Angular 材质数据表排序方向为空状态?
- google-cloud-dlp - 使用 Cloud DLP 时出现 BigQuery 表错误中的未知字段
- python - 在仅将非内部代码行打印到屏幕的跟踪模式下运行 python 脚本
- inno-setup - 在 Inno Setup 中使用“signonce”标志有什么意义?
- python - 将 df 转换为列表列表