Search code examples
javagroovysubstringindexof

Get nth substring of string with common delimiter


I'm working in a groovy web console and want to get the 3rd and last substring that is delimited by /. I've been able to get the last substring using lastIndexOf() and could get the first if desired, but for the life of me I haven't been able to find anything quick and simple to get the index of the second and third occurrence of / so that I can extract the third substring. My desired output from my code below would be:

Produce
Apples

In my sample I am currently printing the pathDelim just for sanity check so ignore why that's there. Sorry if this is a simple question but I'm new to groovy and primarily come from a SQL background where this would be an easy and quick task. Thanks in advance!

productPath = "Store/Grocery/Produce/Apples";

int pathDelim = productPath.lastIndexOf('/');
itemName = (productPath.substring(pathDelim + 1));

println pathDelim;
println itemName;

Solution

  • Have you considered just splitting the string?

    ​productPath.split('/')[2, 3].each {
        println it
    }
    

    Prints your desired output:

    Produce
    Apples
    

    If you need all the indexes you can do

    ​productPath.findIndexValues { it == '/' }
    

    Which returns

    [5, 13, 21]