简体   繁体   中英

Java Extract part of string

I want to extract the value 0.81 from the following string, but I don't know how. Using JSON doesn't work, because as far as I know it's not proper JSON code.

[{"boundingbox":{"size":{"height":239.23,"width":239.23},"tl":{"y":46.15,"x":166.92}},"name":"152:0.81,","confidence":0.9}]

Do you have any idea how to do that?

If this is JSON, which it appears to be, load it up as a JSON Object and

JSONArray jsonArray = new JSONArray(thatString);
JSONObject jObj = jsonArray.getJSONObject(0);
String name = jObj.getString("name");

Which would then give you a string "152:0.81,", an odd name - however I would then split it:

String[] tokens = name.split(":");

tokens[0] will be 152

tokens[1] will be 0.81,

It actually is valid Json, so you could use Json library (any of them), to load the Json to an Object and access the value - If you're having problems loading this into an Object, perhaps you can change your question and show us the error?

If, by any chance, you might get a response that isn't valid Json, you might use a regex:

If you always have that same pattern, something like:

\"name\":\"\d+:(\d\.\d+),\" 

Your value will be in capturing group one.

If you're not sure how to use regexes in Java, just search SO or Google, there's a ton of examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM