How to sort this string and rebuild the same sorted string again


How can I sort values in this string based on the integral parts i.e.





Obviously a regular sort must do in this case but I am not sure about where should I trim the strings compare and rebuild the exact string with optimized approach.

If each [] specifies a unique range of values, you can extract all numbers, sort them and then construct the resultant string back by grouping two elements in each [].

Pattern pattern = Pattern.compile("(\\d+)");
Matcher matcher = pattern.matcher(s);
Set<Integer> numbers = new TreeSet<>();

while(matcher.find()) {

Next step would be to iterate over numbers and use the current and next index to form the resultant string.

An even better approach is to split the string on ; and use @Sergey N Lukin's Comparator to sort the values

    String s = "[160,190];[650,790];[901,974];[401,540];[60,90];";
    String[] values = s.split(";");
    Set<String> sortedValues = new TreeSet<>(new TokensComparator());

Eventually, join the set's elements with a semi-colon(;) using a loop or Google Guava's Joiner