java 将一个字符串里连续两个及以上数字反转

时间:2023-01-07 10:21:58

所要的效果:

oldStr>>>123asd1256fsad12345fe1e12et56789sdf1af123
newStr>>>321asd6521fsad54321fe1e21et98765sdf1af321

 1 public static void main(String[] args) {
 2   String str = "123asd1256fsad12345fe1e12et56789sdf1af123";
 3   System.out.println("oldStr>>>"+str);
 4   StringBuffer newStr = new StringBuffer();
 5   String[] strArray = str.split("\\d{2,}+");
 6   String[] newStrArray = new String[strArray.length];
 7 
 8   for(int i=0;i<strArray.length;i++){
 9     newStr.append(strArray[i]);
10     if(i+1<strArray.length){
11       newStrArray[i] = str.substring(str.indexOf(strArray[i]), str.indexOf(strArray[i+1]));
12     }else{
13       newStrArray[i] = str.substring(str.indexOf(strArray[i]), str.length());
14     }
15     newStrArray[i] =new StringBuffer(newStrArray[i].replace(strArray[i], "")).reverse().toString();
16     newStr.append(newStrArray[i]==null?"":newStrArray[i]);
17 
18   }
19   System.out.println("newStr>>>"+newStr);
20 
21 }