java索引 2 超出范围_StringIndexOutOfBoundsException:字符串索引超出范围:

当没有']'字符或它出现在[〜之前]时,会出现例外(带负数)。如果你想找到[〜...]的所有可能性,你也可以让正则表达式完成这项工作:import java.util.regex.Matcher;import java.util.regex.Pattern;static Pattern p=Pattern.compile("\\[~([^]]+)\\]");

public static void main(String[] args) {

String commentBody="41]5646[~james]64[~marc]s6";

Matcher m=null;

int startIndex=0;

while((m=p.matcher(commentBody)).find(startIndex))

{

String name=m.group(1);

String displayName="michael"; // your logic here to convert to new name

commentBody=commentBody.replace("[~"+name+"]", "[~"+displayName+"]");

startIndex+=displayName.length()+3;

System.out.println(name+" Found at position:"+m.start()+" to "+m.end());

}

System.out.println("result:"+commentBody);}

输出是:james Found at position:7 to 15marc Found at position:19 to 26result:41]5646[~michael]64[~michael]s6

编辑:添加解决方案来替换名称。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值