Search code examples
javastringsubstringlastindexof

Java substring using lastindexOf return a specific length


I'm using JAVA and I have a string called example that looks like;

example = " id":"abcd1234-efghi5678""tag":"abc" "

NOTE: I have't escaped the "'s using \ but you get the idea..

...I want to just return;

abcd1234

...I've been trying using substring

example = (example.substring(example.lastIndexOf("id\":\"")+5));

(because this string could be anywhere in a HTML/JSON File) which kinda works all the lastIndexOf does is find it and then keep everything AFTER it - i.e it returns;

abcd1234-efghi5678""tag":"abc"

Basically I need to find the lastIndexOf based on the string and limit it returns afterwards - I found that I could do it another substring command like this;

example = (example.substring(example.lastIndexOf("id\":\"")+5));
example = example.substring(0,8);

...but it seems messy. Is there any way of using lastIndexOf and also setting a max length at the same time - it's probably something really simple that I can't see due to staring at it for so long.

Many thanks in advance for your help!


Solution

  • Don't substring twice. Use the found index twice instead:

    int idx = example.lastIndexOf("id\":\"");
    example = example.substring(idx + 5, idx + 13);
    

    Or, if the length is dynamic, but always ends with -:

    int start = example.lastIndexOf("id\":\"");
    int end = example.indexOf('-', start);
    example = example.substring(start + 5, end);
    

    In real code, you should of course always check that the substring is found at all, i.e. that idx / start / end are not -1.