Obtaining a substring value for a delimited String of unknown length

Viewed 46

Given the String data, delimited by : and comma separated

String times =  6:10000:first,12:12000:second,18:15000:third

I need to get the third value from the last comma separated list, in this above case 15000

Or 20000 in the below case

String times =  6:10000:first,12:12000:second,18:15000:third,24:20000:fourth

Or 30000 in the below case

String times =  
         6:10000:first,12:12000:second,18:15000:third,24:20000:fourth,30:30000:fourth

Something like:

public String getLastTimeFromCommaSeparatedList() {
    return times.substring(mileages.lastIndexOf(':') + 2);
}

I'm unclear how I can get the value I need, given the comma separated list is of an unknown length.

2 Answers

You can use substring with lastIndexOf and split like this:

times.substring(time.lastIndexOf(",")).split(":")[1]

Demo

String[] times = {"6:10000:first,12:12000:second,18:15000:third",
        "6:10000:first,12:12000:second,18:15000:third,24:20000:fourth",
        "6:10000:first,12:12000:second,18:15000:third,24:20000:fourth,30:30000:fourth"
};
for (String time : times) {
    System.out.println(
            time.substring(time.lastIndexOf(",")).split(":")[1]
    );
}

Outputs

15000
20000
30000

You can use regular expression.

String times = "6:10000:first,12:12000:second,18:15000:third,24:20000:fourth,30:30000:fourth";
java.util.regex.Pattern pttrn = java.util.regex.Pattern.compile("(\\d+):[a-z]+$");
java.util.regex.Matcher mtchr = pttrn.matcher(times);
if (mtchr.find()) {
    System.out.println(mtchr.group(1));
}
else {
    System.out.println("Nothing found.");
}

Explanation of the pattern

  • (\\d+) a string of one or more digits.
  • : the colon character
  • [a-z]+ one or more lowercase letters
  • $ the end of the input string

So the pattern looks for digits followed by a colon followed by lowercase letters at the end of the input string. It also groups the digits.

It works for every sample string in your question.

Related