fork download
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3.  
  4. public class Main {
  5. public static void main(String[] args) {
  6. // Tests
  7. String[] samples = { "123ABC458", "123ABC458XYZ", "123ABC458XYZ367", "ABC123XYZ", "ABC123XYZ" };
  8. for (String s : samples)
  9. System.out.println(numbersInverted(s));
  10.  
  11. }
  12.  
  13. static String numbersInverted(String str) {
  14. StringBuilder sb = new StringBuilder();
  15. Matcher matcher = Pattern.compile("\\d+").matcher(str);
  16. int lastInitialPos = 0;
  17. while (matcher.find()) {
  18. int start = matcher.start();
  19. String inverted = new StringBuilder(matcher.group()).reverse().toString();
  20. sb.append(str.substring(lastInitialPos, start)).append(inverted);
  21. lastInitialPos = matcher.end();
  22. }
  23. if (sb.length() == 0) // If no number was found
  24. return str;
  25. else
  26. return sb.append(str.substring(lastInitialPos)).toString();
  27. }
  28. }
Success #stdin #stdout 0.09s 48024KB
stdin
Standard input is empty
stdout
321ABC854
321ABC854XYZ
321ABC854XYZ763
ABC321XYZ
ABC321XYZ