Java substring using lastindexOf return a specific length

3.8k Views Asked by At

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!

2

There are 2 best solutions below

1
On BEST ANSWER

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.

0
On

You can use a regex to find the specific substring:

String regex = "^id[^a-z0-9]+([a-zA-Z0-9]+)-.*$";
Matcher p = Pattern.compile(regex).matcher(example);

String result = null;
if (p.matches()) {
    result = p.group(1);
}

System.out.println(result); //outputs exactly "abcd1234"

The pattern uses a capturing group that matches id followed by non-alphanumeric characters and preceding -.