当没有']'字符或它出现在[〜之前]时,会出现例外(带负数)。如果你想找到[〜...]的所有可能性,你也可以让正则表达式完成这项工作: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
编辑:添加解决方案来替换名称。