String digest = "111电子元件电子元器件,电子元件电子元器件,电子元件电子元器件[bankDepositExp]"; if(digest.contains("[bankDepositExp]")){ digest = digest.replace("[bankDepositExp]","银行存款支出"); }

如果[bankDepositExp]前面有数据则在前面加逗号,如果后面有数据则在后面加逗号,如果前后都有数据则前后都加逗号,然后再把"[bankDepositExp]"替换为"银行存款支出"

String digest = "111*电子元件*电子元器件,*电子元件*电子元器件,*电子元件*电子元器件[bankDepositExp]";
int startIndex = digest.indexOf("[bankDepositExp]");
int endIndex = startIndex + "[bankDepositExp)".length();

// 检查是否需要在前方添加逗号
boolean prependComma = startIndex > 0 && !Character.isWhitespace(digest.charAt(startIndex - 1));
// 检查是否需要在后方添加逗号,这里直接判断结束索引是否小于字符串长度即可,因为][bankDepositExp]肯定是结尾了
boolean appendComma = endIndex < digest.length() - 1;

// 构建最终的替换字符串,考虑逗号的添加
String replacement = (prependComma ? "," : "") + "银行存款支出" + (appendComma ? "," : "");

// 执行替换
digest = digest.substring(0, startIndex) + replacement + digest.substring(endIndex);

System.out.println(digest);