Best method to get substring after a given word in a String?

118 Views Asked by At

I have a long String, which is a json files contents. Somewhere in this String, it contains the following: "totalWinAmount":100

To find and return this value, I'm currently doing this:

int totalWinAmountIndex = line.lastIndexOf("totalWinAmount");
String resultTotalWinAmount = line.substring(totalWinAmountIndex + 16, totalWinAmountIndex + 19);

This works, resultTotalWinAmount is correctly set to 100, but I'm curious if this is the best practise for a situation like this, whether this is actually awful coding, or if there's a better way of doing it?

2

There are 2 best solutions below

0
On

You could also try to extract the value with the use of regex. Something like this should work:

resultTotalWinAmount = str.split(".*\"totalWinAmount\"\\s*:\\s*")[1].split("\\D+")[0];

That's a bit messy, but works without additional libraries.

However, I agree with Sun. For proper analysis of json you should always use something like Jackson or GSON.

0
On

You can use RegExp: "\s*totalWinAmount\s*"\s*:\s*(?<totalWinAmount>\d*)

This is Demo at regex101.com

This is the most simpliest way to get couple of values (I think that using json converter is overhead for this reason). But if you want to find more values, then definitely, you have to use json converter (e.g. Jackson).